(transfer) javascript wrapper type

https://github.com/stone0090/javascript-lessons/tree/master/1.11-PrimitiveWrapperObjects
Primitive Wrapper Types

To facilitate manipulating primitive values, JavaScript also provides 3 special reference types: Boolean, Number and String. In fact, whenever a basic type value is read, an object of the corresponding basic wrapper type is created in the background, allowing us to call some methods to manipulate the data. Take a look at the example below.

var s1 = "some text";
var s2 = s1.substring(2);
The variable s1 in this example contains a string, which of course is a primitive value. The next line calls the substring() method of s1 and stores the returned result in s2. We know that primitive values ​​are not objects, so logically they shouldn't have methods (though they do, as we'd like). In fact, in order for us to realize this intuitive operation, a series of processing has been automatically completed in the background. When the second line of code accesses s1, the access process is in a read mode, which is to read the value of the string from memory. When accessing strings in read mode, the following processes are automatically performed in the background.

Creates an instance of type String;
invokes the specified method on the instance;
destroys the instance.
Think of the above three steps as executing the following JavaScript code.

var s1 = new String("some text");
var s2 = s1.substring(2);
s1 = null;
After this processing, the basic string value becomes the same as the object. Moreover, the above three steps are also applicable to Boolean and Number values ​​corresponding to Boolean and Number types, respectively.

The main difference between reference types and primitive wrapper types is the lifetime of the object. Instances of reference types created with the new operator remain in memory until the flow of execution leaves the current scope. The automatically created object of the basic wrapper type exists only at the moment of execution of a line of code, and is then destroyed immediately. This means that we cannot add properties and methods to primitive values ​​at runtime. Consider the following example:

var s1 = "some text";
s1.color = "red";
console.log(s1.color); // undefined
Of course, Boolean, Number and String can be called explicitly to create basic wrappers type of object. However, you should do this only when absolutely necessary, because it's easy to tell if you're dealing with a "primitive type" or a "reference type" value. Calling typeof on an instance of a primitive wrapper type returns "object", and all objects of the primitive wrapper type are converted to the boolean value true.

The Object constructor also acts like a factory method, returning an instance of the corresponding primitive wrapper type based on the type of the passed in value. For example:

var obj = new Object("some text");
console.log(obj instanceof String); // true
passing a string to the Object constructor will create an instance of String; passing a numeric parameter will get a Number , passing in the Boolean parameter will get an instance of Boolean.

It should be noted that using new to call the constructor of a primitive wrapper type is not the same as calling the cast function of the same name directly. For example:

var value = "25";
var number = Number(value); // transformation function
console.log(typeof number); // "number"

var obj = new Number(value); // constructor
console.log (typeof obj); // "object"
Although we do not recommend explicitly creating objects of primitive wrapper types, their ability to manipulate primitive values ​​is quite important. Instead, each primitive wrapper type provides convenience methods for manipulating the corresponding value.

 Boolean type

The Boolean type is a reference type that corresponds to a Boolean value. To create a Boolean object, call the Boolean constructor and pass in a true or false value as follows.

var booleanObject = new Boolean(true);
An instance of type Boolean overrides the valueOf() method to return the base type value true or false; overrides the toString() method to return the strings "true" and "false". However, Boolean objects are not very useful in JavaScript because they are often misunderstood. One of the most common problems is using Boolean objects in Boolean expressions, for example:

var falseObject = new Boolean(false);

console.log(result); // true

var falseValue = false;
result = falseValue && true;
console.log(result); // false
In this example, we create a Boolean object with the false value. This object is then combined with the primitive value true to form a logical AND expression. In Boolean operations, false && true equals false. However, this line of code in the example is evaluating falseObject instead of its value false. All objects in a boolean expression are converted to true, so a falseObject object represents true in a boolean expression. As a result, true && true is of course equal to true.

There are two other differences between primitive types and reference type booleans. First, the typeof operator returns "boolean" for primitive types and "object" for reference types. Second, since a Boolean object is an instance of the Boolean type, using the instanceof operator to test a Boolean object returns true, while testing for a primitive boolean value returns false. For example:

console.log(typeof falseObject); // object
console.log(typeof falseValue); // boolean
console.log(falseObject instanceof Boolean); // true
console.log(falseValue instanceof Boolean);
It's important to understand the difference between primitive Boolean values ​​and Boolean objects, and our advice is to never use Boolean objects.

 Number type

Number is a reference type that corresponds to a numeric value. To create a Number object, you can pass it the appropriate numeric value when calling the Number constructor. Below is an example.

var numberObject = new Number(10);
Like the Boolean type, the Number type also overrides the valueOf(), toLocaleString() and toString() methods. The overridden valueOf() method returns the value of the primitive type represented by the object, and the other two methods return the value as a string. You can pass a radix parameter to the toString() method, telling it to return the string form of the decimal value, as shown in the following example.

var num = 10;
console.log(num.toString()); // "10"
console.log(num.toString(2)); // "1010"
console.log(num.toString(8)); // "12"
console.log(num.toString(10)); // "10"
console.log(num.toString(16)); // "a"
In addition to the inherited methods, the Number type provides methods for formatting numeric values ​​as strings. Among them, the toFixed() method will return the string representation of the value according to the specified decimal place, for example:

var num = 10;
console.log(num.toFixed(2)); // "10.00"
Here, the value 2 is passed to the toFixed() method, which means to display several decimal places. Thus, the method returns "10.00", with the necessary number of decimal places padded with 0. If the value itself contains more decimal places than specified, values ​​close to the specified maximum decimal places are rounded, as shown in the following example.

var num = 10.005; console.log(num.toFixed(2)); // The automatic rounding of
"10.01" makes the toFixed() method well suited for monetary values. However, it should be noted that the rounding rules set by different browsers for this method may be different. IE8 and earlier cannot correctly round values ​​in the range {(-0.94,-0.5],[0.5,0.94)} when 0 is passed to toFixed(). For values ​​in this range, IE8 will return 0, not -1 or 1; other browsers will return the correct value. IE9 fixes this problem. The toFixed() method can represent values ​​with 0 to 20 decimal places. But this is only the scope of the standard implementation, some browsers may also support more digits. Another method that can be used to format numbers is toExponential(), which returns a string representation of the number in exponential notation (also known as e-notation). Like toFixed(), toExponential() takes a parameter, which also specifies the number of decimal places in the output. See the example below. var num = 10; console.log(num.toExponential(1)); // "1.0e+1"











The above code outputs "1.0e+1"; however, e notation is generally unnecessary for such small values. If you want to get the most appropriate format for representing a value, you should use the toPrecision() method.

For a numeric value, the toPrecision() method may return a fixed-size (fixed) format or an exponential (exponential) format; the specific rules depend on which format is most appropriate. This method accepts one parameter, the number of digits representing all digits of the value (excluding the exponent part). See the example below.

var num = 99;
console.log(num.toPrecision(1)); // "1e+2"
console.log(num.toPrecision(2)); // "99"
console.log(num.toPrecision(3 )); // The
first task completed by the code above "99.0" is to represent 99 in one digit, and the result is "1e+2", which is 100. Because one digit cannot represent 99 exactly, toPrecision() rounds it up to 100, so it can be represented by one digit. And the next two digits represent 99, of course, "99". Finally, when trying to represent 99 in three digits, the toPrecision() method returns "99.0" . In fact, toPrecision() decides whether to call toFixed() or toExponential() depending on the value to be processed. All three methods can be rounded up or down to represent the value with the correct decimal places in the most accurate form.

The toPrecision() method can represent 1 to 21 decimal places. But this is only the scope of the standard implementation, some browsers may also support more digits.
Like Boolean objects, Number objects also provide important functionality for numeric values ​​in a behind-the-scenes fashion. But at the same time, we still do not recommend instantiating the Number type directly, for the same reasons as explicitly creating a Boolean object. Specifically, when using the typeof and instanceof operators to test primitive values ​​and reference values, the results are completely different, as shown in the following example.

var numberObject = new Number(10);
var numberValue = 10;
console.log(typeof numberObject); // "object"
console.log(typeof numberValue); // "number"
console.log(numberObject instanceof Number); / / true
console.log(numberValue instanceof Number); // false
String type

String type is an object wrapper type of string, which can be created using String constructor as follows.

var stringObject = new String("hello world");
String object methods are also accessible on all primitive string values. Among them, the inherited valueOf(), toLocaleString() and toString() methods all return the basic string value represented by the object.

Each instance of the String type has a length property that indicates that the string contains more than one character. Take a look at the example below.

var stringValue = "hello world";
console.log(stringValue.length); // 11
It should be noted that even if the string contains double-byte characters (not one-byte ASCII characters), each character is still count as one character. For example:

var stringValue = "Hello everyone";
console.log(stringValue.length); // 3 The
String type provides many methods to assist in parsing and manipulating strings in JavaScript.

Character Methods

Two for accessing specific characters in a string are: charAt() and charCodeAt(). Both methods receive one parameter, the 0-based character position. Among them, the charAt() method returns the character at the given position as a one-character string (there is no character type in JavaScript). For example:

var stringValue = "hello world";
console.log(stringValue.charAt(1)); // "e"
If what you want is not a character but a character encoding, then use charCodeAt() like this. For example:

var stringValue = "hello world";
console.log(stringValue.charCodeAt(1)); // 101, 101 is the character code for the lowercase "e"
ECMAScript 5 also defines another method for accessing individual characters. In supporting browsers, you can use square brackets followed by a numeric index to access specific characters in a string, as shown in the following example.

var stringValue = "hello world";
console.log(stringValue[1]); // "e"
string manipulation methods

The following introduces several methods related to manipulating strings. The first is concat(), which is used to concatenate one or more strings and return the concatenated new string. Let's look at an example first.

var stringValue = "hello ";
var result = stringValue.concat("world");

console.log(result); // "hello world"
console.log(stringValue); // "hello"
actually, concat() The method can accept any number of parameters, which means that any number of strings can be concatenated through it. Another example:

var stringValue = "hello ";
var result = stringValue.concat("world", "!");

console.log(result); // "hello world!"
console.log(stringValue); / / "
Although concat() is a method dedicated to concatenating strings, the plus operator + is used more in practice. Also, using the plus operator + is easier in most cases than using the concat() method (especially when concatenating multiple strings).

JavaScript also provides three methods for creating new strings based on substrings: slice(), substr(), and substring(). All three methods return a substring of the string being manipulated, and all accept one or two arguments. The first parameter specifies where the substring begins, and the second parameter (if specified) indicates where the substring ends. Specifically, the second argument to slice() and substring() specifies the position after the last character of the substring. The second parameter of substr() specifies the number of characters returned. If no second parameter is passed to these methods, the length of the string is used as the end position. Like the concat() method, slice(), substr(), and substring() do not modify the value of the string itself, they just return a primitive string value and have no effect on the original string. See the example below.

var stringValue = "hello world";
console.log(stringValue.slice(3)); // "lo world"
console.log(stringValue.substring(3)); // "lo world"
console.log(stringValue. substr(3)); // "lo world"
console. log(stringValue. slice(3, 7)); // "lo w"
console.log(stringValue.substring(3,7)); // "low"
console.log(stringValue.substr(3, 7)); // "lo worl"
when the parameter passed to these methods is negative , they behave differently. Among them, the slice() method will add the incoming negative value to the length of the string, the substr() method will add the negative first parameter to the length of the string, and convert the negative second parameter to 0 . Finally, the substring() method converts all negative arguments to 0. Let's see an example.

var stringValue = "hello world";
console.log(stringValue.slice(-3)); // "rld"
console.log(stringValue.substring(-3)); // "hello world"
console.log(stringValue .substr(-3)); // "rld"
console.log(stringValue.slice(3, -4)); // "low"
console.log(stringValue.substring(3, -4)); / / "hel"
console.log(stringValue.substr(3, -4)); //""


There are two methods for finding substrings in a string: indexOf() and lastIndexOf(). Both methods search a string for a given substring and return the position of the substring (or -1 if the substring is not found). The difference between these two methods is that the indexOf() method searches the substring backwards from the beginning of the string, while the lastIndexOf() method searches forwards from the end of the string for the substring. Let's look at an example.

var stringValue = "hello world";
console.log(stringValue.indexOf("o")); // 4
console.log(stringValue.lastIndexOf("o")); // 7
Both methods can receive The optional second parameter indicates where in the string to start the search. In other words, indexOf() will search backward from the position specified by this parameter, ignoring all characters before that position; and lastIndexOf() will search forward from the specified position, ignoring all characters after that position. See the example below.

var stringValue = "hello world";
console.log(stringValue.indexOf("o", 6)); // 7
console.log(stringValue.lastIndexOf("o", 6)); // 4
is used second In the case of parameters, all matching substrings can be found by calling indexOf() or lastIndexOf() in a loop, as shown in the following example:

var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = stringValue.indexOf("e");

while(pos > -1){
    positions.push(pos);
    pos = stringValue.indexOf("e", pos + 1);
}
console.log(positions); // "3,24,32,35,52"
trim() method

ECMAScript 5 defines trim() for all strings ) method. This method creates a copy of the string, removes all leading and trailing spaces, and returns the result. For example:

var stringValue = " hello world ";
var trimmedStringValue = stringValue.trim();
console.log(stringValue); // " hello world"
console.log(trimmedStringValue); // "hello world"
string case conversion method

There are four methods involved in string case conversion in JavaScript: toLowerCase(), toLocaleLowerCase(), toUpperCase() and toLocaleUpperCase(). Among them, toLowerCase() and toUpperCase() are two classic methods, borrowed from the method of the same name in java.lang.String. The toLocaleLowerCase() and toLocaleUpperCase() methods are implemented for specific regions. For some locales, the locale-specific method yields the same results as the general method, but a few languages ​​(such as Turkish) apply special rules for Unicode case conversion, in which case the locale-specific method must be used to ensure correct implementation conversion. Here are a few examples.

var stringValue = "hello world";
console.log(stringValue.toLocaleUpperCase()); // "HELLO WORLD"
console.log(stringValue.toUpperCase()); // "HELLO WORLD"
console.log(stringValue.toLocaleLowerCase( )); // "hello world"
console.log(stringValue.toLowerCase()); // "hello world"
is generally used when you don't know what locale your code will run in The regional approach is more robust.

Pattern matching methods for strings

The String type defines several methods for matching patterns in strings. The first method is match(), and calling this method on a string is essentially the same as calling RegExp's exec() method. The match() method takes only one parameter, either a regular expression or a RegExp object. Take a look at the example below.

var text = "cat, bat, sat, fat";
var pattern = /.at/;

// same as pattern.exec(text)
var matches = text.match(pattern);
console.log(matches.index); // 0
console.log(matches[0]); // "cat"
console.log(pattern.lastIndex); // 0
Another method for finding patterns is search(). The only parameter to this method is the same as that of the match() method: a regular expression specified by a string or RegExp object. The search() method returns the index of the first match in the string; if no match is found, it returns -1. Also, the search() method always looks for the pattern backwards from the beginning of the string. See the example below.

var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
console.log(pos); // 1, the first occurrence of "at"
To simplify the operation of replacing substrings, JavaScript provides the replace() method. This method accepts two parameters: the first parameter can be a RegExp object or a string (this string will not be converted to a regular expression), and the second parameter can be a string or a function. If the first argument is a string, only the first substring will be replaced. The only way to replace all substrings is to provide a regular expression and specify the global g flag as shown below.

var text = "cat, bat, sat, fat";
var result = text.replace("at", "ond");
console.log(result); // "cond, bat, sat, fat"

result = text .replace(/at/g, "ond");
console.log(result); // "cond, bond, sond, fond" The
last method related to pattern matching is split(), which can be based on the specified The delimiter splits a string into substrings and places the results in an array. The delimiter can be either a string or a RegExp object (this method does not treat the string as a regular expression). The split() method accepts an optional second parameter that specifies the size of the array to ensure that the returned array does not exceed the given size. See the example below.

var colorText = "red,blue,green,yellow";
var colors1 = colorText.split(","); // ["
var colors2 = colorText.split(",", 2); // ["red", "blue"]
localeCompare() method

This method compares two strings and returns one of the following values:

if the string is in the letter The table should be sorted before the string parameter, and a negative number is returned (-1 in most cases, the specific value depends on the implementation);
if the string is equal to the string parameter, it returns 0;
if the string is in the letter Should be listed after the string parameter in the table, a positive number is returned (1 in most cases, the exact value is also implementation-dependent).
Below are a few examples.

var stringValue = "yellow";      
console.log(stringValue.localeCompare("brick")); // 1
console.log(stringValue.localeCompare("yellow")); // 0
console.log(stringValue.localeCompare(" zoo")); // -1
This example compares the string "yellow" with several other values: "brick", "yellow" and "zoo". Because "brick" comes before "yellow" in the alphabet, localeCompare() returns 1; "yellow" equals "yellow", so localeCompare() returns 0; finally, "zoo" comes in the alphabet after "yellow", so localeCompare() returns -1. Again, since the value returned by localeCompare() is implementation-dependent, it is best to use this method as shown in the following example.

function determineOrder(value) {
    var result = stringValue.localeCompare(value);
    if (result < 0){
        console.log("The string 'yellow' comes before the string '" + value + "'.");
    } else if (result > 0) {
        console.log("The string 'yellow' comes after the string '" + value + "'.");





determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
Using this structure, you can ensure that your code will work correctly in any implementation.

What makes the localeCompare() method unique is that the locale (country and language) supported by the implementation determines the behavior of this method. For example, the United States uses English as the standard language for JavaScript implementations, so localeCompare() is case-sensitive, so uppercase precedes lowercase letters in the alphabet as a decisive comparison rule. However, this may not be the case in other regions.

The fromCharCode() method

In addition , the String constructor itself has a static method: fromCharCode(). The task of this method is to receive one or more character encodings and convert them into a string. Essentially, this method does the opposite of the instance method charCodeAt(). Here's an example:

console.log(String.fromCharCode(104, 101, 108, 108, 111)); // "hello"

var s = 'hello';
for(let i=0;i<s.length; i++){
  console.log(`${s[i]}----${s[i].charCodeAt()}`);
}
/*
"h----104"
"e---- 101"

"l----108"
"o----111"
*/
Here, we pass fromCharCode() the character encoding of each letter in the string "hello".

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326506852&siteId=291194637