String extension

1. Includes (), startWith(), and endWith() methods

let str = 'Hello World';
console.log(str.includes('llo'));	//true
console.log(str.startWith('He'));	//true
console.log(str.endWith('ld'));		//true
Copy the code

2. Repeat () method

let str = 'abc';
console.log(str.repeat(3));		//abcabcabc
Copy the code

Remember to pass the parameter integer, pass decimal will be rounded, array objects and so on, do not embarrass others library function.

3. PadStart () and padEnd() methods

PadStart (n, STR)/padEnd(n, STR), fill the string before or after it until the entire string length == n:

let str = 'x';
console.log(str.padStart(4, 'ab'));		//abax
console.log(str.padEnd(4, 'ab'));		//xaba
Copy the code

But only if the length of the original string is less than n, the operation is not performed if the length is greater than n:

let str = 'xxxxx';
console.log(str.padStart(4, 'ab'));		//xxxxx
Copy the code

Application: Month and date:

let year = '2020'; let month = '9'; let day = '9'; console.log(year + month.padStart(2,'0') + day.padStart(2, '0')); / / 20200909Copy the code

4. String template

} can be a variable, an expression, or a function call

let [a, b, c] = [1, 2, 3];
let s = `<ul>
	<li>${a}</li>
    <li>${b}</li>
    <li>${c + b}</li>
</ul>`;
console.log(s);		
Copy the code

Output:

Second, numerical extension

1. Binary and octal representation

0b stands for binary

let a1 = 0b0101; console.log(a1); / / 5Copy the code

The beginning of 0o represents octal

let b1 = 0o77; console.log(b1); / / 63Copy the code

2. The parseInt () and parseFloat ()

Same as number.parseint ()

console.log(Number.parseInt === parseInt);	//true
Copy the code

3.Number.isInteger()

IsInterger () is used to determine whether the Number is an integer.

let a = 1;
let b = 1.5;
console.log(Number.isInteger(a), Number.isInteger(b));		//true false
Copy the code

Realization principle, with the whole down to judge

function myIsInteger(a){ return Math.floor(a) === a; } the console. The log (myIsInteger (1.5)); //falseCopy the code

4.Number.EPSILON

Represents a constant that is extremely small

console.log(Number.EPSILON); / / 2.220446049250313 e-16Copy the code

Often used for error checking

function withErrorMargin(left, right){
	return Math.abs(left - right) < Number.EPSILON;
}
withErrorMargin(0.1 + 0.2, 0.3);		//true
Copy the code

5. Security integer number.issafeINTEGER (), number.max_safe_INTEGER ()

console.log(Number.isSafeInteger(5)); //true console.log(Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1)); //false console.log(Number.MAX_SAFE_INTEGER); / / 9007199254740991Copy the code

6. The Math extension API

6.1 Trunc () Deletes the decimal part

In ES5, math.floor () can also be rounded, but it is rounded down. If the object is negative, it is not the same as what we want, so we have a more convenient trunc:

Let a = 1.5; Let b = 1.5; console.log(Math.floor(a), Math.floor(b)); //1 -2 console.log(Math.trunc(a), Math.trunc(b)); / / 1-1Copy the code

6.2 Cube root of math.cbrt () method

console.log(Math.cbrt(27)); / / 3Copy the code

The cube root method in ES5

Console. log(math.pow (27, 1/3)) // 1/3 power base 27Copy the code

6.3 Math.hypot() take the sum of squares of all the data and take the square root

With two parameters, it’s the same thing as finding the hypotenuse of a right triangle

console.log(Math.hypot(3, 4)); / / 5Copy the code

And then there’s the logarithm, the sine, the cosine, and I’ll look it up again.

Third, function extension

1. Arrow function

Case 1: Only one argument, one return

Var f = function(a){return a + 1; } // let f = a => a + 1; // Simplify a lotCopy the code

Case 2: No arguments, only one return

Var f = function(){return 'a'; } // let f = () => 'a';Copy the code

Case 3: Multiple arguments, one returned

Var f = function(a, b, c){return a + b + c; } // let f = (a, b, c) => a + b + c;Copy the code

Case 4: There are multiple statements in the function

Var f1 = function(a, b){var c = 0; c += a * a; c += b * b; c = Math.sqrt(c); return c; } // let f2 = (a, b) => {let c = 0; c += a * a; c += b * b; c = Math.sqrt(c); return c; }Copy the code

Case 5: Special case: when only one object is returned

Var f11 = function(a, b){return {a: a, b: b}} let f21 = (a, b) => ({a: a, b: a); b}); The console. The log (f21 (1, 2));Copy the code

Case 6: combination of arrow functions and deconstructed assignments

var f1 = function({a, b}){
    var c = Math.sqrt(a * a + b * b);
    return c;
}

var obj = {a: 3, b: 4};
console.log(f1(obj));

let f2 = ({a, b}) => {
    let c = Math.sqrt(a * a + b * b);
    return c;
}
console.log(f1(obj));
Copy the code

Case 7: Common applications

Parameter processing in map ()

console.log([1, 2, 3].map(function(x){ return x * x; })); console.log([1, 2, 3].map(x => x * x)); / / 1 4 9Copy the code

Simplification of sort ()

console.log([1, 5, 2, -3].sort(function(a, b){ return a - b; })); console.log([1, 5, 2, -3].sort((a, b) => a - b)); / / [3, 1, 2, 5]Copy the code

Case 8: REST parameters

let [a, ...args] = [1, 2, 3, 4]; console.log(args); //[2, 3, 4] //1 is assigned to a and the remaining values are assigned to argsCopy the code

For simplifying functions

Function f1(a,... args){ return args; } // let f2 = (a,... args) => args;Copy the code

Case 9: The arrow function’s this is defined when it is defined, not when it is called

// ES5
function f(){
    setTimeout(function(){
        console.log(this.id);	//undefined
    }, 1000);
}
f.call({id:5});		
Copy the code

Because the call ID of F. call is given to f, the function function in setTimeout has its own this, so it prints undefined

// ES6
function f(){
    setTimeout(() => {console.log(this.id)}, 1000); 	//1
}

let obj = {id: 1}

f.call(obj);
Copy the code

Since the arrow function does not initialize this, it looks up into the parent scope and prints 1.

Case 10: Arrow functions cannot be constructors, otherwise an error is reported

Because the arrow function doesn’t have this in it

let f2 = () => {
    this.a = 1;
    this.b = 2;
};

let a = new f2();
Copy the code

Case 11: Arrow functions cannot use arguments objects, use rest arguments instead

// ES5 var f1 = function(){ console.log(arguments); // [] } f1(1, 2, 3, 4); // ES6 let f2 = (... args) => { console.log(args); } f2(1, 2, 3, 4);Copy the code

Case 12: Nested arrow functions: Arrow functions have nested arrow functions

This is called the plumbing mechanism

// ES5 function f1(... args1){ console.log(args1); return {f2: function(... args2){ console.log(args2); return {f3: function(... args3){ console.log(args3); }}; }}; } var c = f1(1, 2, 3).f2(4, 5, 6).f3(7, 8, 9); //[1, 2, 3] [4, 5, 6] [7, 8, 9] // ES6 let f1 = (... args) => ({f2: (... args) => ({f3: (... args3) => {console.log(args3); }})}) var c = f1(1, 2, 3).f2(4, 5, 6).f3(7, 8, 9); / / [7, 8, 9]Copy the code

2. Default values of function parameters

Case 1: Basic usage of default values

The default value is not set

function f(x, y){ x = x || 'Hello'; y = y || 'World'; console.log(x, y); } f(); //Hello World f('Lao Wang'); // Lao Wang World f('Lao Wang', ''); // Problem 1: Expecting the output to be empty, the actual output is Lao Wang WorldCopy the code

To solve problem 1 above, you can set the default value

function f2(x = 'Hello', y = 'World'){
    console.log(x, y);
}
f2('Lao Wang', '');		//Lao Wang
f2('Lao Wang');			//Lao Wang World
Copy the code

Case 2: Arguments to function defaults cannot be declared twice

2.1 Cannot declare variables that are the same as parameters

function f(x = 5){ const x = 3; } f(); // An error is reported at runtimeCopy the code

2.2 When a parameter has a default value, it cannot be repeated

function f(x, x, y = 1){ console.log(x, y); } f(3, 4, 5); / / an errorCopy the code

To duplicate declarations, parameters cannot be assigned default values

function f(x, x, y){ console.log(x, y); } f(3, 4, 5); / / 4 5Copy the code

2.3 The calculation of parameter defaults is lazy

Each call recalculates the expression in the argument

let x = 9; function f(y = x + 1){ console.log(y); } f(); //10 x = 10; f(); / / 11Copy the code

Case 3: Combination of function defaults and destruct defaults

function f({a = 0, b = 0} = {a: 3}){ console.log(a, b); } f({a: 3, b: 4}); //3 4 f({a: 3}); //3 0 f({}); //0 0 f(); / / 3 to 0Copy the code

{a: 3}} {a: 3}

Case 4: Method of argument omission

Method of omitting parameters in deconstructing assignments

let [, b, c] = [1, 2, 3]; console.log(b, c); / / 2, 3Copy the code

But you can’t do that in a function

function f(x, y = 2, z){ console.log(x, y); } f( , 4, 3); // error pass parameter f(undefined, 4, 3); // Pass the parameter correctlyCopy the code

Case 5: function length: the number of required arguments that the function needs

console.log((function(a, b, c){}).length); //3 console.log((function(){}).length); //0 console.log((function(a, b, c = 0){}).length); //2 console.log((function(a = 1, b, c = 0, d ){}).length); / / 2Copy the code

If there is a default value, it does not count in length from the time the default value appears

Case 6: Name of the function

Declaration of functions

function f(){
    console.log('hello');
}

console.log(f.name);		// f
Copy the code

Expression of a function

let f2 = function(){
    console.log('hello');
} 

console.log(f2.name);		//f2
console.log((f2.bind({})).name);	//bound f2
Copy the code

Case 7: Binding and calling this

Use and differences between call, aplay and bind

let obj = { a: 25 }; function f(a, b){ console.log(this.a, a, b); } f.call(obj, 1, 2); // 25 1 2 f.apply(obj, [1, 2]); // 25 1 2 F.biind (obj)(1,2); 25 1 / / 2Copy the code

4. Array extension

1. Extension operators… (REST parameter)

Destruct assignment for arrays

let [a, ...args] = [1, 2, 3, 4]; console.log(args); // 1, 2, 3, 4Copy the code

Used for passing function arguments

let f = (a, ... args) => {console.log(args)}; f(1, 2, 3, 4); / / 1 2 3 4Copy the code

Reverse reading of an array

console.log(... [1, 2, 3)); / / 1 2 3Copy the code

2…. Often used in place of apply

function f(){ console.log(arguments); } let args = [3, 4, 5]; f(args[0], args[1], args[2]); // 3 4 5 f.apply(null, args); // 3 4 5 f(... args); / / 3, 4, 5Copy the code

Application 1: Find the maximum value in the array

let a = [1, 2, 3]; console.log(Math.max(1, 3, 5)); console.log(Math.max.apply(null, a)); console.log(Math.max(... a));Copy the code

Application 2: Concatenate two arrays

let arr1 = [0, 1, 2]; let arr2 = [3, 4, 5]; Array.prototype.push.apply(arr1, arr2); arr1.push(... arr2); console.log(arr1); console.log(arr1.concat(arr2)); console.log([...arr1, ...arr2]);Copy the code

3. The extended variable must be the last one; otherwise, an error is reported

let [a, ...b] = [1, 2, 3, 4]; // let [a,...b, c] = [1, 2, 3, 4]; / / an errorCopy the code

4. Strings can also use extension variables

console.log([...'hello']); / / [' h ', 'h', 'l', 'o', 'o'] / / want to achieve the same effect, ES5 operation so var STR = 'hello'; var strArr = str.split('');Copy the code

5. Turn class arrays into arrays

5.1 Custom class arrays

let arrayLike = {
    '0': '1',
    '1': '25',
    '2': 'abc',
    length: 3
}

// ES5
// let array = Array.prototype.slice.call(arrayLike);
let array = [].slice.call(arrayLike);
console.log(array);		//  ["1", "25", "abc"]

// ES6
let array2 = Array.from(arrayLike);
console.log(array2);	//  ["1", "25", "abc"]
Copy the code

5.2 the DOM NodeList

let divs = document.querySelectorAll('div');
console.log(divs.__proto__.constructor.name);	// NodeList
console.log(divs);		

let array = Array.from(divs);
console.log(array.__proto__.constructor.name);		//Array
console.log(array);
Copy the code

5.3 Function arguments

function f(){
    console.log(arguments.__proto__.constructor.name);		//object
    console.log(arguments);

    let args = Array.from(arguments);
    console.log(args.__proto__.constructor.name);		// Array
    console.log(args);
}

f(1, 2, 3, 4);
Copy the code

6.Array.of: Turns scattered data into arrays

let a = [1, 2, 3]; // [1, 2, 3] let b = new Array(3); Let c = array.of (3); // [3] console.log(a, b, c); / / [1, 2, 3]Copy the code

Find (), findIndex() writes a callback function

Find () can be a function that finds values that match conditions

let a = [1, 4, -3, 9];
console.log(a.find(x => x < 0));		// -3
console.log(a.find((value, index, arr) => {
    console.log(value, index, arr);
    return value < 0;
}));
Copy the code

Find the index that matches the conditional value

console.log(a.findIndex((value, index, arr) => {
    console.log(value, index, arr);
    return value < 0;
}));
Copy the code

Find the value of NaN, which is harder to do in ES5

let b = [1, 4, NaN];
console.log(b.findIndex((value, index, arr) => {
    console.log(value, index, arr);
    return Object.is(NaN, value);	
}));
Copy the code

Object. Is is required, not isNan, because NaN == NaN is false

8. Array instance fill()

let a = new Array(5); a.fill(0); console.log(a); // [0, 0, 0, 0, 0] let b = new Array(5); b.fill(0, 1, 3); Console.log (b); // [, 0, 0, 0,]Copy the code

9. Array instance entries(), keys(), values()

Traverse the subscript

let a = [1, 2, 3, 4]; for(let index of a.keys()){ console.log(index); // 0 1 2 3}Copy the code

Traverse value

for(let elem of a.values()){ console.log(elem); // 1 2 3 4}Copy the code

Iterate over the subscripts and values

for(let [index, elem] of a.entries()){ console.log(index, elem); // 0 1, 1 2, 2 3, 3 4}Copy the code

Output subscripts and values one by one

let entries = a.entries(); console.log(entries.next().value); // 0 1 console.log(entries.next().value); / / 1. 2Copy the code

10. Array instance includes()

let a = [1, 2, 5, NaN];
console.log(a.includes(2));		// true
console.log(a.includes(10));	// false
console.log(a.includes(NaN));	// true
Copy the code

Better than indexOf: 1. Semantic, 2. NaN