JavaScript Advanced Programming (4th edition) Reading Notes

Chapter 5 _ Basic reference types

A reference value (or object) is an instance of a particular reference type. Reference types are sometimes called object definitions because they describe the properties and methods that their objects should have. Reference types are a bit like classes, but they are not the same thing. Objects are considered instances of a particular reference type. A new object is created by using the new operator followed by a constructor. Constructors are functions used to create new objects, such as this line of code:

let now = new Date(a);Copy the code

This line creates a new instance of the reference type Date and stores it in the variable now. Date(), in this case, is the constructor that creates a simple object with only default properties and methods.

This paper mainly

A reference value (or object) is an instance of a particular reference type. Reference types are sometimes called object definitions because they describe the properties and methods that their objects should have. Several built-in reference types are provided in ECMAScript for developers to use:

  • The Date type is used to provide Date and time information. It contains helper methods such as date.parse () and date.utc ().
  • The RegExp type is used for regular expressions. Regular expressions can be used in many ways, but I always read them and forget them again. I hope you can learn them by heart and write more examples to impress you.
  • Boolean, Number, and String objects of the corresponding primitive wrapper types.
  • Built-in objects: Global and Math. Both object code will exist in the global context at the start of execution.

These are all reference types that are easy for developers to develop, but I personally feel like they are more of a convenience object that contains methods that are faster to implement our needs.

5.1 the Date

The Date type references java.util.date in earlier versions of Java. To do this, the Date type stores the Date as the number of milliseconds that have passed since midnight of Universal Time Coordinated (UTC) January 1, 1970. Using this storage format, the Date type can accurately represent dates 285,616 years before and after January 1, 1970.

Without passing arguments to the Date constructor, the object created will hold the current Date and time. To create a date object based on another date and time, you must pass in its millisecond representation (the number of milliseconds after midnight on January 1, 1970, in the UNIX era). ECMAScript provides two helper methods for this: date.parse () and date.utc ().

The date.parse () method takes a string argument representing a Date and attempts to convert the string to the number of milliseconds representing that Date. Ecma-262 Version 5 defines the Date format date.parse () should support, filling in the blanks left over from version 3. All implementations must support the following date formats:

  • “Month/day/year”, for example, “5/23/2019”;
  • “Month name, day, year”, for example, “May 23, 2019”;
  • Week Date Month name Day Year hour: minute: second Time zone, for example, Tue May 23 2019 00:00:00 GMT-0700.
  • ISO 8601 is in the extended format YYYY-MM-DDTHh: MM: SS. SssZ, for example, 2019-05-23T00:00:00 (applicable only to ES5-compatible implementations).

For example, to create a date object that represents “May 23, 2019”, use the following code:

let someDate = new Date(Date.parse("May 23, 2019")); 
Copy the code

If the string passed to date.parse () does not represent a Date, the method returns NaN. If you pass a string representing a Date directly to the Date constructor, Date calls date.parse () in the background. In other words, the following line of code is equivalent to the previous line:

let someDate = new Date("May 23, 2019"); 
Copy the code

The date.utc () method also returns a millisecond representation of the Date, but uses different information than date.parse () to generate this value. The arguments passed to date.UTC () are year, zero-starting month (January is 0, February is 1, and so on), day (1-31), hour (0-23), minute, second, and millisecond. Of these parameters, only the first two (year and month) are required. If no day is provided, the default is 1 day. The default values for all other parameters are 0. Here are two examples of using date.utc () :

// 0:00 GMT, January 1, 2000
let y2k = new Date(Date.UTC(2000.0)); 
 
// May 5, 2005, 5:55 PM GMT
let allFives = new Date(Date.UTC(2005.4.5.17.55.55)); 
Copy the code

As with date.parse (), date.utc () is called implicitly by the Date constructor, but with one difference: in this case a local Date is created, not a GMT Date. However, the Date constructor takes the same arguments as date.utc (). So, if the first argument is a number, the constructor assumes it is the year in a date, the second argument is the month, and so on.

// midnight local time on January 1, 2000
let y2k = new Date(2000.0); 
 
// 5:55.55 PM local time on 5 May 2005
let allFives = new Date(2005.4.5.17.55.55); 
Copy the code

ECMAScript also provides the date.now () method, which returns the number of milliseconds indicating the Date and time when the method is executed. This method can be easily used in code analysis:

// Start time
let start = Date.now(); 
 
// Call the function
doSomething(); 
 
// End time
let stop = Date.now(),
result = stop - start;
Copy the code

5.1.1 Methods of inheritance

The Date type overrides the toLocaleString(), toString(), and valueOf() methods. But unlike the other types, these methods return different values when overridden. The toLocaleString() method of type Date returns a Date and time consistent with the local environment in which the browser is running. This usually means that the format contains AM (AM) or PM (PM) for time, but no time zone information (the exact format may vary by browser). The toString() method usually returns the date and time with the time zone information, and time is also expressed in 24 hours (0 to 23). Here is an example of the zero of February 1, 2019 returned by toLocaleString() and toString() (PST of “en-US”) :

toLocaleString() - 2/1/2019 12:00:00 AM 
 
toString() - Thu Feb 1 2019 00:00:00 GMT-0800 (Pacific Standard Time)
Copy the code

The valueOf() method of type Date does not return a string at all. This method has been overridden to return a millisecond representation of the Date. Therefore, operators such as less-than and greater-than can directly use the value it returns.

let date1 = new Date(2019.0.1);    // January 1, 2019
let date2 = new Date(2019.1.1);    // 1 February 2019
 
console.log(date1 < date2); // true c
onsole.log(date1 > date2); // false 
Copy the code

5.1.2 Date Formatting method

The Date type has several special methods for formatting dates, all of which return strings:

  • ToDateString () displays the day of the week, month, day, and year in the date (format is implementation-specific);
  • ToTimeString () displays the hours, minutes, seconds, and time zone in the date (format is implementation-specific);
  • ToLocaleDateString () displays the day of the week, month, day, and year in the date (format is implementation – and locale-specific);
  • ToLocaleTimeString () displays hours, minutes, and seconds in the date (format is implementation – and locale-specific);
  • ToUTCString () displays the full UTC date (format is implementation-specific).

The output of these methods, like toLocaleString() and toString(), varies from browser to browser. Therefore, it cannot be used to display dates consistently on the user interface.

5.1.3 Date/Time component method

The remaining methods of the Date type (see the table below) are directly involved in getting or setting specific parts of the Date value. Note that the “UTC date” in the table refers to the date when there is no time zone offset (converting the date to GMT).

5.2 the RegExp

ECMAScript supports regular expressions through the RegExp type. Regular expressions are created using perl-like terse syntax:

let expression = /pattern/flags; 
Copy the code

The pattern of this regular expression can be any simple or complex regular expression, including character classes, qualifiers, grouping, look-forward, and backreferencing. Each regular expression can have zero or more flags that control the behavior of the regular expression. The tags that represent matching patterns are given below.

  • G: Global mode, which looks for the entire content of the string instead of ending with the first match.
  • I: Case insensitive, which means that the case of pattern and string is ignored when searching for matches.
  • M: Multi-line mode, which indicates that the search will continue until the end of a line of text.
  • Y: Adhesion mode, which only looks for strings starting from and after lastIndex.
  • U: Unicode mode, enabling Unicode matching.
  • S: indicates the metacharacter in dotAll mode. Matches any character (including \n or \r).
// Matches all "at" in the string
let pattern1 = /at/g; 
 
// Matches the first "bat" or "cat", ignoring case
let pattern2 = /[bc]at/i; 
 
// Matches all three-character combinations ending in "at", regardless of case
let pattern3 = /.at/gi; 
Copy the code

Metacharacters have one or more special functions in regular expressions, so to match the characters themselves, you must use backslashes to escape them. ([]} {\ ^ $|)? * +

// Matches the first "bat" or "cat", ignoring case
let pattern1 = /[bc]at/i; 
 
// Match the first "[BC]at", ignoring case
let pattern2 = /\[bc\]at/i; 
 
// Matches all three-character combinations ending in "at", regardless of case
let pattern3 = /.at/gi; 
 
// Matches all ".at", ignoring case
let pattern4 = /\.at/gi; 
Copy the code

Regular expressions can also be created using the RegExp constructor, which takes two parameters: a pattern string and, optionally, a token string. Any regular expression defined using literals can also be created using constructors

// Matches the first "bat" or "cat", ignoring case
let pattern1 = /[bc]at/i; 
 
// Same as pattern1, but created with the constructor
let pattern2 = new RegExp("[bc]at"."i"); 
Copy the code

5.2.1 RegExp Instance Attributes

Each RegExp instance has the following properties that provide information about various aspects of the schema. 

  • Global: A Boolean value indicating whether the G flag is set. 
  • IgnoreCase: Boolean value indicating whether the I flag is set.
  • Unicode: Boolean value indicating whether the U flag is set.
  • Sticky: A Boolean value, indicating whether the Y flag is set.
  • LastIndex: Integer representing the start of the next search in the source string, always starting at 0.
  • Multiline: Boolean value indicating whether the M flag is set.
  • DotAll: Boolean value indicating whether the S flag is set.
  • Source: Literal string for the regular expression (not the pattern string passed to the constructor), without leading and ending slashes.
  • Flags: indicates the flag string of the regular expression. Always return as a literal instead of a string pattern passed in to the constructor (no backslashes).
let pattern1 = /\[bc\]at/i; 
 
console.log(pattern1.global);      // false
console.log(pattern1.ignoreCase);  // true 
console.log(pattern1.multiline);   // false 
console.log(pattern1.lastIndex);   / / 0
console.log(pattern1.source);      // "\[bc\]at"
console.log(pattern1.flags);       // "i" 
 
let pattern2 = new RegExp("\\[bc\\]at"."i"); 
 
console.log(pattern2.global);      // false
console.log(pattern2.ignoreCase);  // true
console.log(pattern2.multiline);   // false 
console.log(pattern2.lastIndex);   / / 0
console.log(pattern2.source);      // "\[bc\]at"
console.log(pattern2.flags);       // "i" 
Copy the code

5.2.2 RegExp instance method

The primary method for RegExp instances is exec(), which is used primarily with capture groups. This method takes only one parameter, the string to which the pattern is to be applied. If a match is found, the array containing the first match is returned; If no match is found, null is returned. The Array returned is an instance of Array, but contains two additional attributes: index and input. Index is the starting position of the matching pattern in the string, and input is the string to look for. The first element of this array is a string that matches the entire pattern, and the other elements are strings that match the capture groups in the expression. If there is no capture group in the schema, the array contains only one element.

let text = "mom and dad and baby"; 
let pattern = /mom( and dad( and baby)?) ? /gi; 
 
let matches = pattern.exec(text); 
console.log(matches.index);   / / 0
console.log(matches.input);   // "mom and dad and baby" 
console.log(matches[0]);      // "mom and dad and baby" 
console.log(matches[1]);      // " and dad and baby" 
console.log(matches[2]);      // " and baby" 
Copy the code

5.2.3 RegExp constructor properties

The RegExp constructor also has several attributes of its own. (In other languages, this property is called a static property.)

These properties allow you to extract information related to the operations performed by exec() and test(). Consider the following example:

let text = "this has been a short summer";
let pattern = / (.). hort/g;  
 
if (pattern.test(text)) {   
  console.log(RegExp.input);        // this has been a short summer   
  console.log(RegExp.leftContext);  // this has been a   
  console.log(RegExp.rightContext); // summer  
  console.log(RegExp.lastMatch);    // short  
  console.log(RegExp.lastParen);    // s 
}
Copy the code

The above code creates a pattern to search for any character followed by “HORT” and places the first character in the capture group. The contents of the different attributes are as follows.

  • The input property contains the original string.
  • The leftConext property contains the content before “short” in the original string, and the rightContext property contains the content after “short”.
  • The lastMatch attribute contains the last string to match the entire regular expression, namely “short”.
  • The lastParen attribute contains the last match of the capture group, which is “S”.

5.2.4 Mode Limitations

While ECMAScript support for regular expressions has come a long way, some of the advanced features of the Perl language are still missing. The following features are not currently supported by ECMAScript (for more information, see regular-expressions. Info) :

  • \A and \Z anchors (match the beginning and end of the string, respectively)
  • Union and cross classes
  • Atomic groups
  • X (ignore Spaces) matches the pattern
  • Conditional matching
  • Regular expression comments

5.3 Original value Packaging type

To facilitate manipulation of raw values, ECMAScript provides three special reference types: Boolean, Number, and String. These types have the same characteristics as the other reference types described in this chapter, but also have special behavior corresponding to their respective primitive types. Every time a method or property of a primitive value is used, an object of the corresponding primitive wrapper type is created in the background, exposing the various methods that operate on the primitive value.

let s1 = "some text"; 
let s2 = s1.substring(2); 
Copy the code

In this case, s1 is a variable containing a string, which is a raw value. The second line immediately calls the substring() method on S1 and stores the result in S2. We know that primitive values themselves are not objects, so logically there should be no methods. And in fact this example works exactly as expected. This is because there is a lot of processing going on in the background to make this happen. Specifically, when the second line accesses S1, it does so in read mode, that is, it reads the value that the variable holds from memory. Any time a String value is accessed in read mode, the following three steps are performed in the background: (1) Create an instance of String; (2) call a specific method on the instance; (3) Destroy the instance. Think of these steps as executing the following three lines of ECMAScript code:

let s1 = new String("some text"); 
let s2 = s1.substring(2);
s1 = null; 
Copy the code

The main difference between reference types and raw value wrapper types is the life cycle of the object. After a reference type is instantiated with new, the resulting instance is destroyed when it leaves scope, and the automatically created raw value wrapper object only exists for the execution of the line of code that accessed it. This means that attributes and methods cannot be added to raw values at run time.

The Boolean, Number, and String constructors can be explicitly used to create primitive value wrapper objects. However, you should do this only when you really need to, otherwise it’s easy to confuse the developer with whether they are raw or referenced values. Calling Typeof on an instance of a primitive value wrapper type returns “object”, and all primitive value wrapper objects are converted to a Boolean value true.

5.3.1 Boolean

Boolean is a reference type corresponding to a Boolean value. To create a Boolean object, use the Boolean constructor and pass either true or false, as in the following example:

let booleanObject = new Boolean(true); 
Copy the code

The Boolean instance overrides the valueOf() method, returning a raw valueOf true or false. The toString() method is also overridden when called, returning the string “true” or “false”.

An error-prone concept:

let falseObject = new Boolean(false);
let result = falseObject && true;
console.log(result); // true 
All objects are automatically converted to true in Boolean expressions, so falseObject actually represents a true value in this expression.
 
let falseValue = false; 
result = falseValue && true;
console.log(result); // false 
Copy the code

There are several other differences between original and reference values (Boolean objects). First, the Typeof operator returns “Boolean” for the original value, but “object” for the referenced value. Similarly, a Boolean object is an instance of a Boolean type that returns true when the instaceof operator is used, but false for the original value

console.log(typeof falseObject);             // object 
console.log(typeof falseValue);              // boolean 
console.log(falseObject instanceof Boolean); // true
console.log(falseValue instanceof Boolean);  // false 
Copy the code

5.3.2 Number

Number is the reference type for the corresponding numeric value. To create a Number object, use the Number constructor and pass in a value, as in the following example:

let numberObject = new Number(10); 
Copy the code

As with Boolean, the Number type overrides valueOf(), toLocaleString(), and toString() methods. The valueOf() method returns the raw value represented by the Number object, and the other two methods return numeric strings. The toString() method optionally takes a radix and returns a numeric string in the form of the corresponding radix, as shown below:

let 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" 
Copy the code

In addition to the inherited methods, the Number type provides several methods for formatting numeric values into strings.

The toFixed() method returns a numeric string containing the specified number of decimal places, as in:

let num = 10;
console.log(num.toFixed(2)); / / "10.00"
Copy the code

ToExponential () returns a value string represented in scientific notation (also known as exponential notation). Like toFixed(), toExponential() takes an argument that represents the number of bits in the result, such as:

let num = 10; console.log(num.toExponential(1));  1.0 e+1 "/ /"
Copy the code

The toPrecision() method returns reasonable output, depending on the case, either in fixed-length or scientific notation. This method takes a parameter that represents the total number of digits (not including the exponent) in the result. Let’s look at a few examples:

let num = 99;
console.log(num.toPrecision(1)); // "1e+2" 
console.log(num.toPrecision(2)); / / "99"
console.log(num.toPrecision(3)); / / "99.0"
Copy the code

Essentially, the toPrecision() method determines whether toFixed() or toFixed() is called based on value and accuracy. All three methods are rounded up or down in order to accurately represent values in the correct decimal place.

The Typeof and Instacnceof operators return different results when dealing with raw and reference values:

let numberObject = new Number(10);
let numberValue = 10; 
console.log(typeof numberObject);             // "object" 
console.log(typeof numberValue);              // "number" 
console.log(numberObject instanceof Number);  // true 
console.log(numberValue instanceof Number);   // false 
Copy the code

IsInteger () and secure integers. In ES6, the number.isInteger () method is added to determine whether a value is saved as an integer.

console.log(Number.isInteger(1));    // true 
console.log(Number.isInteger(1.00)); // true 
console.log(Number.isInteger(1.01)); // false 
Copy the code

5.3.3 String

String is the reference type of the corresponding String. To create a String, use the String constructor and pass in a value, as in the following example:

let stringObject = new String("hello world"); 
Copy the code

String methods can be called on all raw String values. The three inherited methods valueOf(), toLocaleString(), and toString() all return the original string valueOf the object.

Each String object has a length attribute that represents the number of characters in the String. str.length

1. The JavaScript characters

JavaScript strings consist of 16-bit code units. For most characters, there is one character for every 16 bits. In other words, the length property of a string indicates how many 16-bit codes the string contains:

let message = "abcde"; 
 
console.log(message.length); / / 5
Copy the code

The charAt() method returns a character at the given index position, as specified by the integer argument passed to the method:

let message = "abcde"; 
 
console.log(message.charAt(2)); // "c" 
Copy the code

Use the charCodeAt() method to view the character encoding of the specified code element. This method returns the symbol value, specified as an integer, at the specified index position.

let message = "abcde"; 
 
// Unicode "Latin Small letter C" is U+0063
console.log(message.charCodeAt(2));  / / 99
 
// Decimal 99 equals hexadecimal 63
console.log(99= = =0x63);            // true 
Copy the code

The fromCharCode() method is used to create characters in a string based on a given UTF-16 code element. This method can take any number of numeric values and return a string concatenating the corresponding characters of all numeric values:

// Unicode "Latin Small letter A" is U+0061
// Unicode "Latin Small letter B" is U+0062
// Unicode "Latin Small letter C" is U+0063
// Unicode "Latin Small letter D" is U+0064
// Unicode "Latin Small letter E" is U+0065
 
console.log(String.fromCharCode(0x61.0x62.0x63.0x64.0x65));  // "abcde" 
 
// 0x0061 === 97 
// 0x0062 === 98 
// 0x0063 === 99 
// 0x0064 === 100 
// 0x0065 === 101 
 
console.log(String.fromCharCode(97.98.99.100.101));          // "abcde" 
Copy the code

2. The normalize () method

Some Unicode characters can be encoded in multiple ways. Some characters can be represented by either a BMP character or a proxy pair. Such as:

// U+00C5: uppercase Latin A circled above
console.log(String.fromCharCode(0x00C5));          / / A
 
// U+212B: length unit "angstrom"
console.log(String.fromCharCode(0x212B));          / / A
 
// U+004: capital Latin letter A
// U+030A: add a circle
console.log(String.fromCharCode(0x0041.0x030A));  / / A
Copy the code

The comparison operator does not care what characters look like, so the three characters are not equal. To solve this problem, Unicode provides four normalized forms that normalize characters like the one above into a consistent format, regardless of the code of the underlying character. The four normalized forms are: There has been much discussion about the following aspects of the university: Normalization (Normalization), Normalization (Normalization), Normalization (Normalization), Normalization (Normalization), Normalization (Normalization), Normalization (Normalization), Normalization (Normalization), Normalization (Normalization) and Normalization (Normalization). You can apply the above normalized form to the string using the normalize() method, passing in a string representing what form: “NFD”, “NFC”, “NFKD”, or “NFKC”.

let a1 = String.fromCharCode(0x00C5),   
    a2 = String.fromCharCode(0x212B),     
    a3 = String.fromCharCode(0x0041.0x030A); 
 
// U+00C5 is the result of NFC/NFKC normalization of 0+212B
console.log(a1 === a1.normalize("NFD"));  // false 
console.log(a1 === a1.normalize("NFC"));  // true 
console.log(a1 === a1.normalize("NFKD")); // false 
console.log(a1 === a1.normalize("NFKC")); // true 
 
// U+212B is unnormalized
console.log(a2 === a2.normalize("NFD"));  // false 
console.log(a2 === a2.normalize("NFC"));  // false 
console.log(a2 === a2.normalize("NFKD")); // false 
console.log(a2 === a2.normalize("NFKC")); // false 
 
// U+0041/U+030A is the result of the NFD/NFKD normalization of 0+212B
console.log(a3 === a3.normalize("NFD"));  // true 
console.log(a3 === a3.normalize("NFC"));  // false 
console.log(a3 === a3.normalize("NFKD")); // true 
console.log(a3 === a3.normalize("NFKC")); // false 

// Select the same normalized form so that the comparison operator returns the correct result:
console.log(a1.normalize("NFD") === a2.normalize("NFD"));    // true 
console.log(a2.normalize("NFKC") === a3.normalize("NFKC"));  // true
console.log(a1.normalize("NFC") === a3.normalize("NFC"));    // true 
Copy the code

3. String operation methods

Concat (), used to concatenate one or more strings into a new string. The concat() method can accept any number of arguments, so it can concatenate multiple strings at once:

let stringValue = "hello "; 
let result = stringValue.concat("world"); 
 
console.log(result);      // "hello world" 
console.log(stringValue); // "hello" 
// Multiple splices:
let resultA = stringValue.concat("world"."!"); 
console.log(result);      // "hello world!" 
console.log(stringValue); // "hello"  
// The original string remains unchanged
Copy the code

Although the concat() method can concatenate strings, the more common way is to use the plus operator (+). And in most cases, it’s more convenient to concatenate multiple strings.

There are three methods for extracting substrings from strings: slice(), substr(), and substring(). Each of these three methods returns a substring of the string from which they were called, and each takes one or two arguments. The first argument represents where the substring starts, and the second argument represents where the substring ends. For slice() and substring(), the second argument is the location where the extraction ends (that is, the characters before that location are extracted). For substr(), the second argument represents the number of substrings returned. In any case, omitting the second parameter means extracting to the end of the string. Like the concat() method, slice(), substr(), and substring() do not modify the string from which they were called, but only return the extracted original new string value.

let 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" 
Copy the code

When a parameter is negative, the three methods behave differently. For example, the slice() method treats all negative arguments as string length plus negative argument values. The substr() method, on the other hand, takes the first negative argument value as the string length and adds it, converting the second negative argument value to 0. The substring() method converts all negative argument values to 0.

let 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));  // "hel"
console.log(stringValue.substr(3, -4));     // "" (empty string) 
Copy the code

4. String position method

There are two methods used to locate substrings within a string: indexOf() and lastIndexOf(). These two methods search for the incoming string from the string and return the position (-1 if none is found). The difference is that the indexOf() method looks for substrings from the beginning of the string, while the lastIndexOf() method looks for substrings from the end.

let stringValue = "hello world"; 
console.log(stringValue.indexOf("o"));     / / 4
console.log(stringValue.lastIndexOf("o")); / / 7
Copy the code

Both methods can accept an optional second parameter indicating where to start the search. This means that indexOf() searches toward the end of the string starting at the position specified by this argument, ignoring characters that precede that position; LastIndexOf () searches the beginning of the string from the position indicated by this argument, ignoring characters from that position up to the end of the string.

let stringValue = "hello world"; 
console.log(stringValue.indexOf("o".6));     / / 7
console.log(stringValue.lastIndexOf("o".6)); / / 4
Copy the code

5. String contains methods

ECMAScript 6 adds three methods to determine if a string contains another string: startsWith(), endsWith(), and includes(). Each of these methods searches for the incoming string from the string and returns a Boolean value indicating whether it is contained or not. The difference is that startsWith() checks matches starting at index 0, endsWith() checks matches starting at call (string.length-substring.length), and includes() checks the entire string:

let message = "foobarbaz"; 
 
console.log(message.startsWith("foo"));  // true 
console.log(message.startsWith("bar"));  // false 
 
console.log(message.endsWith("baz"));    // true 
console.log(message.endsWith("bar"));    // false 
 
console.log(message.includes("bar"));    // true 
console.log(message.includes("qux"));    // false 
Copy the code

The startsWith() and includes() methods accept an optional second parameter indicating where to start the search. Passing a second argument means that the two methods search from the specified position toward the end of the string, ignoring all characters up to that position. Here’s an example:

let message = "foobarbaz"; 
 
console.log(message.startsWith("foo"));     // true 
console.log(message.startsWith("foo".1));  // false 
 
console.log(message.includes("bar"));       // true 
console.log(message.includes("bar".4));    // false 
Copy the code

The endsWith() method takes an optional second argument indicating the position that should be taken as the end of the string. If this parameter is not provided, the default is string length. If provided, it is as if the string has only so many characters:

let message = "foobarbaz"; 
 
console.log(message.endsWith("bar"));     // false 
Copy the code

6. The trim () method

The trim () method. This method creates a copy of the string, removes all preceding and following Spaces, and returns the result. Such as

let stringValue = " hello world "; 
let trimmedStringValue = stringValue.trim();
console.log(stringValue);         // " hello world "
console.log(trimmedStringValue);  // "hello world" 
Copy the code

Since trim() returns a copy of the string, the original string is unaffected, meaning that the original pre-and post-whitespace characters are preserved. In addition, the trimLeft() and trimRight() methods are used to clean up Spaces from the beginning and end of the string, respectively.

7. Repeat () method

ECMAScript provides the repeat() method on all strings. This method takes an integer argument indicating how many times to copy the string, and then returns the result of concatenating all the copies.

let stringValue = "na "; 
console.log(stringValue.repeat(16) + "batman");
// na na na na na na na na na na na na na na na na batman 
Copy the code

8. PadStart () and padEnd() methods

The padStart() and padEnd() methods copy the string and, if less than the specified length, populate the corresponding side with characters until the length condition is met. The first argument to both methods is length and the second argument is an optional padding string, which defaults to a space (U+0020)

let stringValue = "foo"; 
 
console.log(stringValue.padStart(6));       // " foo"
console.log(stringValue.padStart(9."."));  / / "... foo"
 
console.log(stringValue.padEnd(6));         // "foo "
console.log(stringValue.padEnd(9."."));    // "foo......" 
Copy the code

The optional second argument is not limited to one character. If a string of more than one character is provided, it is concatenated and truncated to match the specified length. Also, if the length is less than or equal to the string length, the original string is returned.

let stringValue = "foo"; 
 
console.log(stringValue.padStart(8."bar")); // "barbafoo" 
console.log(stringValue.padStart(2));        // "foo" 
 
console.log(stringValue.padEnd(8."bar"));   // "foobarba" 
console.log(stringValue.padEnd(2));          // "foo" 
Copy the code

9. String iteration and deconstruction

The string prototype exposes an @@iterator method that iterates over each character of the string. Iterators can be used manually as follows:

let message = "abc"; 
let stringIterator = message[Symbol.iterator](); 
 
console.log(stringIterator.next());  // {value: "a", done: false} 
console.log(stringIterator.next());  // {value: "b", done: false} 
console.log(stringIterator.next());  // {value: "c", done: false} 
console.log(stringIterator.next());  // {value: undefined, done: true} 
Copy the code

10. String case conversion

The next set of methods involves case conversion and consists of four methods: toLowerCase(), toLocaleLowerCase(), toUpperCase(), and toLocaleUpperCase(). The toLowerCase() and toUpperCase() methods are pre-existing methods with the same name as those in java.lang.String. The toLocaleLowerCase() and toLocaleUpperCase() methods are designed to be location-specific. In many places, the locale-specific approach is the same as the generic approach. However, in a few languages (such as Turkish), Unicode capitalization conversions require special rules that require locale-specific methods to achieve the correct conversion.

let 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" 
Copy the code

String pattern matching method

The String type has several methods specifically designed to implement pattern matching in strings. The first is the match() method, which is essentially the same as the exec() method of the RegExp object. The match() method takes an argument, which can be a regular expression string or a RegExp object.

let text = "cat, bat, sat, fat"; 
let pattern = /.at/; 
 
// Equivalent to pattern.exec(text)
let matches = text.match(pattern); 
console.log(matches.index);      / / 0
console.log(matches[0]);         // "cat" 
console.log(pattern.lastIndex);  / / 0
Copy the code

The array returned by the match() method is the same as the array returned by the exec() method of the RegExp object: the first element is a string that matches the entire pattern, and the remaining elements are strings that match the capture group in the expression, if any.

Another string method for finding patterns is search(). The only argument to this method is the same as to the match() method: a regular expression string or a RegExp object. This method returns the index of the first matching position of the pattern, or -1 if none is found. Search () always matches patterns backwards from the beginning of the string. Look at the following example:

let text = "cat, bat, sat, fat";
let pos = text.search(/at/);
console.log(pos);  / / 1
Copy the code

To simplify substring substitution, ECMAScript provides the replace() method. This method takes two arguments. The first argument can be a RegExp object or a string (which is not converted to a regular expression), and the second argument can be a string or a function. If the first argument is a string, only the first substring is replaced. To replace all substrings, the first argument must be a regular expression with a global flag, as shown in the following example:

let text = "cat, bat, sat, fat"; 
let 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" 
Copy the code

In case the second argument is a string, there are several special character sequences that can be used to insert the value of the regular expression operation. Ecma-262 specifies the values in the following table.

Using these special sequences, you can use the previously matched content in the replacement text, as shown in the following example:

let text = "cat, bat, sat, fat"; 
result = text.replace(/(.at)/g."word ($1)"); 
console.log(result);  // word (cat), word (bat), word (sat), word (fat) 
Copy the code

The second argument to replace() can be a function. When there is only one match, the function receives three arguments: the string that matches the entire pattern, the start position of the match in the string, and the entire string. In the case of multiple capture groups, each string matching each capture group is also passed to the function as an argument, but the last two arguments are still the starting position and the original string matching the entire pattern. This function should return a string indicating what to replace the match with. Using a function as the second argument gives you more detailed control over the substitution process, as shown below:

function htmlEscape(text) {  
  return text.replace(/[<>"&]/g.function(match, pos, originalText) {   
    switch(match) {     
    case "<":         
      return "&lt;";      
    case ">":      
      return "&gt;";      
    case "&":       
      return "&amp;";     
    case "\" ":       
      return "&quot;"; }}); }console.log(htmlEscape("

Hello world!

"
)); // "< p class=" greeting" > Hello world!

"
Copy the code

The last string method associated with pattern matching is split(). This method splits the string into arrays based on the delimiter passed in. The delimiter argument can be a string or a RegExp object. (String delimiters are not treated as regular expressions by this method.) You can also pass in a second argument, the array size, to ensure that the returned array does not exceed the specified size. Consider the following example:

let colorText = "red,blue,green,yellow";
let colors1 = colorText.split(",");       // ["red", "blue", "green", "yellow"] 
let colors2 = colorText.split(",".2);    // ["red", "blue"] 
let colors3 = colorText.split(/ [^,] + /);   // ["", ",", ",", ",", "]
Copy the code

12. LocaleCompare () method

The final method is localeCompare(), which compares two strings and returns one of the following three values.

  • Returns a negative value if the string should precede the string arguments in alphabetical order. (Usually -1, depending on the implementation associated with the actual value.)
  • Returns 0 if the string is equal to the string argument.
  • If in alphabetical order the string should come after the string arguments, a positive value is returned. (Usually 1, depending on the implementation associated with the actual value.)

Here’s an example:

let stringValue = "yellow";
console.log(stringValue.localeCompare("brick"));  / / 1
console.log(stringValue.localeCompare("yellow")); / / 0
console.log(stringValue.localeCompare("zoo"));    // -1 
Copy the code

13. The HTML method

Early browser developers saw a need to use JavaScript to dynamically generate HTML tags. As a result, early browsers extended the specification to include ways to assist in generating HTML tags. The following table summarizes these HTML methods. However, these methods have largely gone out of use because the results are usually not semantically marked.

5.4 Singleton built-in Objects

Built-in objects are defined as “any object provided by an ECMAScript implementation, independent of the host environment, and existing at the beginning of execution of an ECMAScript program.”

5.4.1 Global

The Global object is a special object in ECMAScript because code does not explicitly access it. Ecma-262 defines the Global object as a backstop object that targets properties and methods that do not belong to any object. In fact, there is no such thing as a global variable or function. Variables and functions defined in the Global scope become properties of the Global object. The functions described earlier in this book, including isNaN(), isFinite(), parseInt(), and parseFloat(), are actually methods of Global objects. In addition to these, there are other methods on the Global object.

1. URL encoding method

The encodeURI() and encodeURIComponent() methods are used to encode the Uniform resource Identifier (URI) for passing to the browser. Valid URIs cannot contain certain characters, such as Spaces. Encoding URIs using URI encodings allows browsers to understand them, while replacing all invalid characters with special UTF-8 encodings. The ecnodeURI() method is used to encode the entire URI, such as “www.wrox.com/illegal value.js”. The encodeURIComponent() method is used to encode individual components in the URI, such as “illegal value.js” in the previous URL. The main difference between the two methods is that encodeURI() does not encode special characters that are part of the URL component, such as colons, slashes, question marks, and hashes, whereas encodeURIComponent() encodeURIComponent() encodes any non-standard characters it finds.

let uri = "http://www.wrox.com/illegal value.js#start"; 
 
// "http://www.wrox.com/illegal%20value.js#start"
console.log(encodeURI(uri)); 
 
// "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start" 
console.log(encodeURIComponent(uri)); 
Copy the code

The opposite of encodeURI() and encodeURIComponent() are decodeURI() and decodeURIComponent(). DecodeURI () decodes only characters encoded with encodeURI(). For example, %20 is replaced with a space, but %23 is not replaced with a hash sign (#) because hash signs are not replaced by encodeURI(). Similarly, decodeURIComponent() decodes all characters encoded by encodeURIComponent(), which basically decodes all special values.

let uri = "http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.js%23start"; 
 
// http%3A%2F%2Fwww.wrox.com%2Fillegal value.js%23start console.log(decodeURI(uri)); 
 
// http:// www.wrox.com/illegal value.js#start console.log(decodeURIComponent(uri)); 
Copy the code

2. The eval () method

This method is a complete ECMAScript interpreter that takes a single parameter, an ECMAScript (JavaScript) string to be executed.

eval("console.log('hi')"); 
// This line of code is equivalent to the next line:
console.log("hi"); 
eval("function sayHi() { console.log('hi'); }");
sayHi(); 
Copy the code

When the interpreter finds an eval() call, it interprets the arguments as actual ECMAScript statements and inserts them into that location. The code executed through eval() belongs to the context of the call, and the code executed has the same scope chain as that context. This means that variables defined in the containment context can be referenced inside an eval() call.

In strict mode, variables and functions created inside eval() cannot be accessed externally. Similarly, in strict mode, assigning to eval causes an error.

3. Global object properties

4. The window object

Although ECMA-262 does not specify how to access Global objects directly, browsers implement window objects as proxies for Global objects. Therefore, all variables and functions declared in the global scope become properties of the window.

var color = "red"; 
 
function sayColor() {   console.log(window.color); } 
 
window.sayColor(); // "red" 
Copy the code

Another way to get a Global object is to use the following code:

let global = function() {   return this; } ();Copy the code

This code creates an immediate function expression that returns the value of this. As mentioned earlier, this is equal to the Global object when a function is executed without specifying this explicitly (either by a method that becomes an object, or by call()/apply()). Therefore, calling a function that simply returns this is a common way to get a Global object in any execution context.

5.4.2 Math

ECMAScript provides Math objects as a place to store mathematical formulas, information, and calculations. The Math object provides properties and methods that aid in computation.

1. Math object properties

2. Min () and Max () methods

The min() and Max () methods are used to determine small and large values in a set of values. Both methods take any number of arguments

let max = Math.max(3.54.32.16); 
console.log(max);  / / 54
 
let min = Math.min(3.54.32.16);
console.log(min);  / / 3
Copy the code

To learn about large and small values in arrays, use the extension operator as follows:

let values = [1.2.3.4.5.6.7.8]; 
let max = Math.max(... val);Copy the code

3. Rounding method

Four methods for rounding small values to integers: math.ceil (), math.floor (), math.round (), and math.fround ().

  • The math.ceil () method always rounds up to close integers.
  • The math.floor () method always rounds down to close integers.
  • The math.round () method performs rounding.
  • The math.fround () method returns a single-precision (32-bit) floating-point representation of close numeric values.
console.log(Math.ceil(25.9));   / / 26
console.log(Math.ceil(25.5));   / / 26
console.log(Math.ceil(25.1));   / / 26
 
console.log(Math.round(25.9));  / / 26
console.log(Math.round(25.5));  / / 26
console.log(Math.round(25.1));  / / 25
 
console.log(Math.fround(0.4));  / / 0.4000000059604645
console.log(Math.fround(0.5));  / / 0.5
console.log(Math.fround(25.9)); / / 25.899999618530273
 
console.log(Math.floor(25.9));  / / 25
console.log(Math.floor(25.5));  / / 25
console.log(Math.floor(25.1));  / / 25
Copy the code

4. The random () method

The math.random () method returns a random number in the range 0 to 1, including 0 but not 1.

number = Math.floor(Math.random() * total_number_of_choices + first_possible_value) 
// Range of 1-10 random numbers
let num = Math.floor(Math.random() * 10 + 1); 
Copy the code

5. Other methods

5.5 summary

Objects in JavaScript are called reference values, and several built-in reference types can be used to create objects of a specific type.

  • Reference values are similar to classes in traditional object-oriented programming languages, but the implementation is different.
  • The Date type provides information about the Date and time, including the current Date, time, and associated calculations.
  • The RegExp type is an ECMAScript interface that supports regular expressions and provides most of the basic and some advanced regular expression functionality.

One of the things that makes JavaScript unique is that functions are actually instances of type Function, which means functions are also objects. Because functions are objects, they also have methods that can be used to enhance their capabilities.

Because of the primitive value wrapper type, primitive values in JavaScript can be used as objects. There are three primitive value wrapper classes: Boolean, Number, and String. They all have the following characteristics.

  • Each wrapper type maps to a primitive type of the same name.
  • When raw values are accessed in read mode, an object of raw value wrapper type is instantiated in the background, with which the corresponding data can be manipulated.
  • After the statement involving the original value completes, the wrapped object is destroyed.

When the code starts executing, there are two built-in objects in the Global context: Global and Math. Of these, the Global object is not directly accessible in most ECMAScript implementations. However, the browser implements it as a Window object. All Global variables and functions are properties of the Global object. The Math object contains properties and methods that aid in complex calculations.

References:

JavaScript Advanced Programming (Version 4)