To facilitate the operation of basic type values, JavaScript also provides three special reference types: Boolean, Number, and String. In fact, every time you read a basic type value, the background will create a corresponding BASIC packaging type object, so that we can call some methods to operate on the data. To facilitate the operation of basic type values, JavaScript also provides three special reference types: Boolean, Number, and String. In fact, every time you read a basic type value, the background will create a corresponding BASIC packaging type object, so that we can call some methods to operate on the data. Let's look at the example below.
var s1 = "some text"; var s2 = s1.substring(2);
In this example, the variable s1 contains a string, which is of course a basic type value. The next line calls the substring () method of s1 and stores the returned results in s2. We know that basic type values are not objects, So logically they should not have methods (although they do have methods as we wish ). In fact, in order to achieve this intuitive operation, the background has automatically completed a series of processing. When the second line of code accesses s1, the access process is in a read mode, that is, to read the value of this string from the memory. When accessing strings in Read mode, the background will automatically complete the following processing.
Creates an instance of the String type;
Call the specified method on the instance;
Destroy this instance.
The preceding three steps can be considered 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. The preceding three steps also apply to Boolean and Number values corresponding to the Boolean and Number types.
The main difference between the reference type and the basic packaging type is the lifetime of the object. Instances of the reference type created using the new operator are stored in the memory until the execution stream leaves the current scope. The automatically created basic packaging type object only exists in the execution instant of a line of code and is immediately destroyed. This means that we cannot add attributes and methods for basic type values at runtime. Let's look at the following example:
var s1 = "some text"; s1.color = "red"; console.log(s1.color); // undefined
Of course, you can explicitly call Boolean, Number, and String to create objects of the basic packaging type. However, this should be done if absolutely necessary, because it is easy to tell whether you are processing the value of the "Basic Type" or "reference type. If typeof is called for an instance of the basic packaging type, "object" is returned, and all objects of the basic packaging type are converted to a Boolean value of true.
The Object constructor returns an instance of the corresponding BASIC packaging type based on the input value type, just like the factory method. For example:
var obj = new Object("some text"); console.log(obj instanceof String); // true
If you pass the String to the Object constructor, a String instance is created. If you pass in a value parameter, the Number instance is obtained. If you pass in a Boolean parameter, a Boolean instance is obtained.
Note that using new to call constructors of the basic packaging type is different from directly calling transformation functions of the same name. 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 it is not recommended to explicitly create objects of the basic packaging type, their ability to operate on basic type values is still very important. Each basic packaging type provides a convenient way to operate the corresponding value.
Boolean Type
The Boolean type is the reference type corresponding to the Boolean value. To create a Boolean object, call the Boolean constructor as follows and pass in a value of true or false.
var booleanObject = new Boolean(true);
A Boolean-type instance overwrites the valueOf () method, returns the true or false value of the basic type, overwrites the toString () method, and returns the "true" and "false" strings ". However, Boolean objects are not very useful in JavaScript because they often cause misunderstandings. The most common problem is to use a Boolean object in a Boolean expression. For example:
var falseObject = new Boolean(false); var result = falseObject && true; console.log(result); // true var falseValue = false; result = falseValue && true; console.log(result); // false
In this example, a Boolean object is created with the value of false. Then, the object and the basic type value true constitute the logic and expression. In Boolean operations, false & true is equal to false. However, in the example, this line of code is used to evaluate falseObject rather than its value false. All objects in the Boolean expression are converted to true. Therefore, the falseObject object represents true in the Boolean expression. In the result, true & true is equal to true.
There are two differences between the basic type and the Boolean value of the reference type. First, the typeof operator returns "boolean" for the basic type, and "object" for the reference type ". Secondly, because the Boolean object is a Boolean-type instance, true is returned when you use the instanceof operator to test the Boolean object, and false is returned when you test the basic-type Boolean value. For example:
console.log(typeof falseObject); // object console.log(typeof falseValue); // boolean console.log(falseObject instanceof Boolean); // true console.log(falseValue instanceof Boolean); // false
It is important to understand the differences between Boolean values of Basic Types and Boolean objects. We recommend that you never use Boolean objects.
Number Type
Number is the reference type corresponding to the numeric value. To create a Number object, you can pass the corresponding value to the Number constructor when calling the Number constructor. The following is an example.
var numberObject = new Number(10);
Like Boolean, the value type also overwrites the valueOf (), toLocaleString (), and toString () methods. The override valueOf () method returns the value of the basic type represented by the object, and the other two methods return the value in the string format. You can pass a base parameter for the toString () method to tell it to return the string format of several hexadecimal values, 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 also provides some methods for formatting numeric values into strings. The toFixed () method returns a numerical string representation based on the specified decimal point. For example:
var num = 10; console.log(num.toFixed(2)); // "10.00"
Here, the toFixed () method is introduced with a value of 2, which indicates how many decimal places are displayed. Therefore, this method returns "10.00", which fills the necessary decimal places with 0. If the number itself contains more decimal places than the specified number, the value close to the specified maximum decimal place will be rounded, as shown in the following example.
var num = 10.005; console.log(num.toFixed(2)); // "10.01"
The feature of automatic rounding makes the toFixed () method suitable for processing currency values.
Note that different browsers may set different rounding rules for this method.
When toFixed () is passed to 0, IE8 and earlier versions cannot properly round the value between {(-0.94,-0.5], [0.5, 0.94. For values in this range, IE8 returns 0 instead of-1 or 1. other browsers can return the correct value. IE9 fixed this issue.
The toFixed () method can represent numbers with 0 to 20 decimal places. But this is only the scope of the standard implementation, and some browsers may support more digits.
In addition, toExponential () is used to format A value. This method returns a string of values in exponential notation (also called e Notation. Like toFixed (), toExponential () also receives a parameter that also specifies the number of decimal places in the output result. Let's look at the example below.
var num = 10; console.log(num.toExponential(1)); // "1.0e+1"
The above code outputs "1.0e + 1"; however, such a small value generally does not need to use e notation. If you want to use the toPrecision () method to indicate the most suitable format for a value.
For a value, the toPrecision () method may return a fixed size (fixed) format or an exponential format. The specific rule is to see which format is the most suitable. This method receives a parameter, that is, the number of digits (excluding the exponent part) of all numeric values ). See the following example.
var num = 99; console.log(num.toPrecision(1)); // "1e+2" console.log(num.toPrecision(2)); // "99" console.log(num.toPrecision(3)); // "99.0"
The first task completed by the above Code is represented by 99 in one digit, and the result is "1e + 2", that is, 100. Because one digit cannot accurately represent 99, toPrecision () rounds it up to 100 so that one digit can be used to represent it. The next two digits represent 99, of course, "99 ". Finally, if you want to represent 99 in three digits, The toPrecision () method returns "99.0 ". In fact, toPrecision () determines whether to call toFixed () or toExponential () based on the value to be processed (). The three methods can be rounded up or down to indicate the value with the correct decimal place 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, and some browsers may support more digits.
Similar to a Boolean object, the Number object provides an important function for numeric values. At the same time, we do not recommend that you instantiate the Number type directly because it is the same as creating a Boolean object explicitly. Specifically, when the typeof and instanceof operators are used to test the value of the basic type and the value of the reference type, the result is 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
The String type is the object packaging type of the String. You can use the String constructor to create it as follows.
var stringObject = new String("hello world");
The String object method can also be accessed in all basic String values. 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 attribute, indicating that the String contains multiple characters. Let's 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 ASCII characters occupying one byte), each character is still considered a single character. For example:
Var stringValue = "Hello everyone"; console. log (stringValue. length); // 3
The String type provides many methods to help parse and operate strings in JavaScript.
Character Method
The two methods used to access specific characters in a string are charAt () and charCodeAt (). Both methods receive a parameter, that is, a 0-based character location. The charAt () method returns the character at the given position in the form of a single character string (JavaScript does not have a character type ). For example:
var stringValue = "hello world"; console.log(stringValue.charAt(1)); // "e"
If you want character encoding instead of character encoding, use charCodeAt () as follows. For example:
Var stringValue = "hello world"; console. log (stringValue. charCodeAt (1); // 101,101 is the character encoding of the lowercase letter "e"
ECMAScript 5 also defines another method for accessing individual characters. You can use square brackets and numerical indexes to access specific characters in a string in a browser, as shown in the following example.
var stringValue = "hello world"; console.log(stringValue[1]); // "e"
String operation method
The following describes several methods related to the Operation string. The first one is concat (), which is used to concatenate one or more strings and return the new concatenated strings. Let's look at an example.
var stringValue = "hello "; var result = stringValue.concat("world"); console.log(result); // "hello world" console.log(stringValue); // "hello"
In fact, the concat () method can accept any number of parameters, that is, it can be used to splice any number of strings. Let's look at another example:
var stringValue = "hello "; var result = stringValue.concat("world", "!"); console.log(result); // "hello world!" console.log(stringValue); // "hello"
Although concat () is specifically used to concatenate strings, in practice, more operators + are used. Furthermore, using the plus sign operator + is easier in most cases than using the concat () method (especially when splicing 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 operated string, and both of them accept one or two parameters. The first parameter indicates the starting position of the sub-string, and the second parameter (when specified) indicates the end of the sub-string. Specifically, the second parameter of slice () and substring () specifies the position after the last character of the substring. The second parameter of substr () specifies the number of returned characters. If the second parameter is not 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 only return a basic string value, does not affect the original string. See the following example.
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)); // "lo w" console.log(stringValue.substr(3, 7)); // "lo worl"
When the parameters passed to these methods are negative, their behavior will be different. The slice () method adds the incoming negative value to the length of the string. The substr () method adds the length of the string to the negative first parameter, the second parameter of the negative value is converted to 0. Finally, the substring () method converts all negative values to 0. The following is 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); // "lo w" console. log (stringValue. substring (3,-4); // "El" console. log (stringValue. substr (3,-4); // "(empty string)
String position method
You can use two methods to search for sub-strings: indexOf () and lastIndexOf (). Both methods search for a given substring from a substring and return the position of the substring (if the substring is not found,-1 is returned ). The difference between the two methods is that the indexOf () method searches for the substring from the beginning of the string, while the lastIndexOf () method searches for the substring forward from the end of the string. 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, indicating the position in the string to start searching. In other words, indexOf () Searches backward from the specified position, ignoring all characters before the specified position; while lastIndexOf () Searches forward from the specified position, ignore all characters after this position. Let's look at the example below.
var stringValue = "hello world"; console.log(stringValue.indexOf("o", 6)); // 7 console.log(stringValue.lastIndexOf("o", 6)); // 4
When the second parameter is used, you can call indexOf () or lastIndexOf () cyclically to find all matched substrings, 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 the trim () method for all strings. This method creates a copy of the string, removes all spaces in the front and suffix, 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-sensitive Conversion Method
There are four methods for string case-sensitivity conversion in JavaScript: toLowerCase (), toLocaleLowerCase (), toUpperCase (), and toLocaleUpperCase (). Here, toLowerCase () and toUpperCase () are two classic methods, which refer to the same name method in java. lang. String. The toLocaleLowerCase () and toLocaleUpperCase () methods are implemented for specific regions. For some regions, the region-specific method has the same result as the general method, but a few languages (such as Turkish) will apply special rules for Unicode case-sensitivity conversion, at this time, the region-specific method must be used to ensure correct conversion. The following are 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"
In general, it is safer to use a region-specific method without knowing in which language the code will run.
String Pattern Matching Method
The String type defines several methods used to match the pattern in the String. The first method is match (). Calling this method on the string is essentially the same as calling RegExp's exec () method. The match () method only accepts one parameter, either a regular expression or a RegExp object. Let's look at the example below.
Var text = "cat, bat, sat, fat"; var pattern = /. at/; // same as pattern.exe c (text) var matches = text. match (pattern); console. log (matches. index); // 0 console. log (matches [0]); // "cat" console. log (pattern. lastIndex); // 0
Another method used for the search mode is search (). The unique parameter of 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 matching item in the string. If no matching item is found,-1 is returned. In addition, the search () method is always in Backward search Mode starting with a string. Let's look at the example below.
Var text = "cat, bat, sat, fat"; var pos = text. search (/at/); console. log (pos); // 1, that is, the location where "at" appears for the first time
To simplify the replacement of 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 parameter is a string, only the first substring is 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 (). This method divides a string into multiple sub-strings Based on the specified separator and places the results in an array. The delimiter can be a string or a RegExp object (this method does not regard the string as a regular expression ). The split () method can accept the optional second parameter, which is used to specify the size of the array to ensure that the returned array does not exceed the specified size. See the following example.
Var colorText = "red, blue, green, yellow"; var colors1 = colorText. split (","); // ["red", "blue", "green", "yellow"] var colors2 = colorText. split (",", 2); // ["red", "blue"] localeCompare () method
This method compares two strings and returns one of the following values:
If the string should be placed before the string parameter in the alphabet, 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, 0 is returned;
If the string should be placed after the string parameter in the alphabet, a positive number is returned (in most cases, it is 1, and the specific value also depends on the implementation ).
The following are 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" exists before "yellow" in the alphabet, localeCompare () returns 1, while "yellow" equals "yellow", so localeCompare () returns 0. Finally, "zoo" is listed after "yellow" in the alphabet, so localeCompare () returns-1. Once again, because the value returned by localeCompare () depends on the implementation, 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 + "'."); } else { console.log("The string 'yellow' is equal to the string '" + value + "'."); } } determineOrder("brick"); determineOrder("yellow"); determineOrder("zoo");
With this structure, you can ensure that your code runs correctly in any implementation.
The localeCompare () method is different in that the supported regions (countries and languages) determine the behavior of this method. For example, the United States uses English as the standard language for JavaScript implementation. Therefore, localeCompare () is case-sensitive. Therefore, the upper-case letters are placed before the lower-case letters in the alphabet and become a decisive comparison rule. However, this is not the case in other regions.
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 then convert them into a string. Essentially, this method is opposite to the instance method charCodeAt. Let's look at an example:
Console. log (String. fromCharCode (104,101,108,108,111); // "hello" var s = 'hello'; for (let I = 0; I
Here, we pass fromCharCode () the character encoding of each letter in the string "hello.
Level
// Challenge 1 var falseObject = new Object (false); console. log (typeof falseObject );//??? Console. log (falseObject instanceof Object );//??? Console. log (falseObject instanceof Boolean );//??? // Challenge 2 var numberObject = new Object (100); console. log (typeof numberObject );//??? Console. log (numberObject instanceof Object );//??? Console. log (numberObject instanceof Number );//??? // Challenge 3 var stringObject = new Object ("abcde"); console. log (typeof stringObject );//??? Console. log (stringObject instanceof Object );//??? Console. log (stringObject instanceof String );//??? // Challenge 4: Flip a string // tip: You can use the array reverse () method var reverse = function (str) {// method body to be implemented} console. log (reverse ("hello"); // "olleh"