preface

This article references JavaScript You Don’t Know (part 2)

From value conversions to mathematical calculations, ES6 adds a number of new static properties and methods for various built-in primitive types and objects to aid in some common tasks. In addition, some instances of primitive types have gained new functionality through the new stereotype approach.

This article will introduceArray.Object.Number.StringFour new built-in objectsapiReading the same book in different stages will have different harvest, maybe this time after serious thinking we will have another way to achieve.

Array

Static functionsArray.of(..)

Array(..) A well-known pitfall of constructors is that if you pass in only one argument, and that argument is a number, instead of constructing an array of single elements with the value of that number, you construct an empty array with the length attribute of that number. This action leads to the unfortunate and bizarre “empty slot” behavior that JavaScript arrays are notorious for.

Array.of(..) Replaced the Array (..) Becomes the recommended function form constructor for arrays because array.of (..) There is no problem with this particular single digit parameter. Consideration:

// Array(..)
var a = Array(3); / / / the empty x 3
a.length;         / / 3
a[0];             // undefined

// Array.of(..)
var b = Array.of(3); / / [3]
b.length;            / / 1
b[0];                / / 3
Copy the code

Static functionsArray.from(..)

A “array-like object” in JavaScript is one that has a length attribute. You can’t use other array apis, such as arguments for functions, and NodeList.

A common requirement is to convert them to real arrays so that various array.Prototype methods can be applied. Array.from(..) Is an elegant and concise way to do it

function test(){
 console.log(Array.from(arguments).map(item= > item))
}
test(1.2.3.4) / / [1, 2, 3, 4]

Copy the code

Prototype methodcopyWithin(..)

Array#copyWithin(..) Is a new modifier method that is supported by all arrays, including typed ones. copyWithin(..) Copies a portion of an array to another location in the same array, overwriting all the original values of that location. The parameters are target (the index to be copied to), start (the source index to start the replication, included), and optional end (the index to end the replication does not include). If any of the arguments is negative, it is treated as the opposite value to the end of the array. Consideration:

[1.2.3.4.5].copyWithin( 3.0 );      / /,2,3,1,2 [1]
[1.2.3.4.5].copyWithin( 3.0.1 );   / /,2,3,1,5 [1]
[1.2.3.4.5].copyWithin( 0, -2 );     / /,5,3,4,5 [4]
[1.2.3.4.5].copyWithin( 0, -2, -1 ); / / (4, 2, 3, 4, 5)
Copy the code

Prototype methodfill(...)

You can use the ES6 native supported method Array#fill(..) Fill an existing set of numbers completely (or partially) with the specified value:

Consider the following code

// Array(..)
var a = Array(3); / / / the empty x 3
a.length;         / / 3
a[0];             // undefined
Copy the code

Now we want each item of the array to be filled with {} by default

var a = Array(3).fill({}) / / / {}, {}, {}
// fill(..) Optionally accept arguments start and end, which specify the location of the subset to populate the array, such as:
var b = Array(3).fill({} , 1.2) // [empty, {}, empty]
Copy the code

Prototype methodentries(),values(),keys()

It may not be considered a “collection” in traditional terms, but it is a collection in the sense that it provides the same iterator methods entries(), values(), and keys(). Consideration:

var a = [1.2.3]; 
[...a.values()];   / / [1, 2, 3]
[...a.keys()];    / / [0]
[...a.entries()]; // [[0,1], [1,2], [3]]
Copy the code

Object

Static functionsObject.is(..)

Static function Object.is(..) Perform a more rigorous value comparison than the === comparison. Consideration:

var x = NaN, y = 0, z = -0; 
x === x;           // false 
y === z;           // true 
Object.is( x, x ); // true 
Object.is( y, z ); // false
Copy the code

If strict identification is requiredNaNor0Value, then it should be selectedObject.is(..).

Static functions Object.getOwnPropertySymbols(..)

Symbol may well become the most commonly used special genus of an image. So we import object.getownPropertySymbols (..). It gets all symbolic attributes directly from the object:

var o = { 
foo: 42[Symbol( "bar") :"hello world".baz: true 
};
Object.getOwnPropertySymbols( o ); // [ Symbol(bar) ]
Copy the code

Static functionsObject.setPrototypeOf(..)

[[Prototype]] sets the object’s [[Prototype]] for behavior delegation, considering:

var o1 = { 
    foo() { console.log( "foo"); }};var o2 = { 
/ /.. The definition of O2..
}; 
Object.setPrototypeOf( o2, o1 ); // Delegate to o1.foo()
o2.foo(); // foo
Copy the code

Static functionsObject.assign(..)

Many JavaScript libraries/frameworks provide tools for copying/mixing attributes from one object into another (e.g., JQuery’s extent(..)). ). There are subtle differences between these different tools, such as whether to ignore an attribute with a value of undefined.

ES6 added object.assign (..) This is a simplified version of these algorithms. The first argument is target, and the other arguments passed in are sources, which are processed in the order listed. For each source, its enumerable and its own (that is, not “inherited”) key values, including symbols, are copied by simple = assignment. Object.assign(..) Returns the target object.

Consider this object setting:

var target = {}, o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 }, o4 = { d: 4 }; 
// Set the read-only property
Object.defineProperty( o3, "e", {
    value: 5.enumerable: true.writable: false.configurable: false});// Set non-enumerable properties
Object.defineProperty( o3, "f", { 
    value: 6.enumerable: false}); o3[Symbol( "g")] =7; 
// Set non-enumerable symbols
Object.defineProperty( o3, Symbol( "h" ), {
value: 8.enumerable: false});Object.setPrototypeOf( o3, o4 ); Only attributes A, B, C, e andSymbol("g") will be copied to target:Object.assign( target, o1, o2, o3 ); 
target.a; / / 1
target.b; / / 2
target.c; / / 3
Object.getOwnPropertyDescriptor( target, "e" ); 
// { value: 5, writable: true, enumerable: true, 
// configurable: true } 
Object.getOwnPropertySymbols( target ); // [Symbol("g")]
Copy the code

Number

What’s more, for the program to work, it has to handle numbers precisely.

ES6 has added additional properties and functions for common number operations.

Two new additions to Number are references to existing global functions: number.parseint (..). And the Number. ParseFloat (..) .

NumberStatic properties of

The minimum difference between any two values of EPSILON: 2^-52

MAX_SAFE_INTEGER The largest integer that JavaScript can express with unambiguous “safe” numeric values: 2^ 53-1

Number.min_safe_integer The smallest integer that JavaScript can express with unambiguous “safe” numeric values: -(2^ 53-1) or (-2)^53 + 1

Static functionsNumber.isNaN(..)

Standard global utility isNaN(..) Flawed since its inception, it returns true for non-numeric things, not just true NaN values, because it casts parameters to numeric types (which can mistakenly result in NaN).

ES6 added a correction tool called number.isnan (..) , can work as expected:

var a = NaN, b = "NaN", c = 42; 
isNaN( a ); // true 
isNaN( b ); // true--oops! 
isNaN( c ); // false 
// ---------------------
Number.isNaN( a ); // true 
Number.isNaN( b ); // false-- fixed!
Number.isNaN( c ); // false
Copy the code

Static functionsNumber.isFinite(..)

See like isFinite (..) Such function names are often thought to mean “non-infinite”. But that’s not entirely true. This new ES6 tool has some subtleties. Consideration:

var a = NaN, b = Infinity, c = 42; 
Number.isFinite( a ); // false 
Number.isFinite( b ); // false 
Number.isFinite( c ); // true
Copy the code

Standard global isFinite(..) The parameter is cast, but number.isFinite (..) Would omit the compulsion:

var a = "42"; 
isFinite( a ); // true 
Number.isFinite( a ); // false
Copy the code

String

Static functionsString.raw(..)

String.raw(..) The utility is provided as a built-in tag function, used with template string literals, to get the raw string without any escape sequences applied.

This function is rarely called manually, but instead is used with label template literals:

var str = "bc"; 
String.raw`\ta${str}d\xE9`; // "tabcd\xE9" instead of" abcde"
Copy the code

The prototype functionrepeat(..)

In languages like Python and Ruby, you can repeat strings like this: “foo” * 3; // “foofoofoo”

JavaScript does not support this form, because multiplication * is only defined for numbers, so “foo” is cast to the word NaN.

However, ES6 defines a string prototype method repeat(..) To complete this task:

"foo".repeat( 3 ); // "foofoofoo"
Copy the code

String checking function

In addition to String#indexOf(..) prior to ES6 And String# lastIndexOf (..) , adding three new search/check methods: startsWith(..) , endsWidth (..) And includes (..) .

var palindrome = "step on no pets"; 
palindrome.startsWith( "step on" ); // true 
palindrome.startsWith( "on".5 );  // true 
palindrome.endsWith( "no pets" );  // true 
palindrome.endsWith( "no".10 );  // true 
palindrome.includes( "on" );      // true 
palindrome.includes( "on".6 );   // false
Copy the code

END