This article makes a lot of reference to MDN because it is relatively authoritative and contains many examples.

Var, let, const

  • Variables declared without keywords default to the window property.
  • Var Specifies the variable declared by default. The default is the window property.

var

  • Variables declared by var are “created” and “initialized” during the execution context creation phase, so they can be used before the declaration for the execution phase.
  • There is variable promotion, and the way a JavaScript engine works is it parses the code, gets all the variables that are declared, and then runs it line by line, and the result is that all variable declarations are promoted to the top of the code, which is called variable promotion
    console.log(a);
    
    var a=1;
    // Print the result without error, only undefined
    Copy the code
  • Var has no block-level scope, only function scope, which is the statement defined in {}.
  • Allow duplicate declarations

let

  • Properties created that do not belong to the top-level object Window are not added to the window by default
  • Duplicate declarations are not allowed. Variables with the same name are not allowed to be declared in the same scope.
  • There is no variable promotion.
  • A temporary dead zone. Variables declared by the LET are only “created” and not “initialized” during the execution context creation phase. Therefore, for the execution phase, if used before its definition execution, it is equivalent to using an uninitialized variable and an error will be reported
  • Block-level scope

const

  • Has let, which is a variable that can be assigned repeatedly. Const constants cannot be “assigned repeatedly.”
  • Const is used to declare one or more constants and must be initialized when declared
  • Const cannot be assigned repeatedly, meaning that the address of a value cannot be changed. The base data types of JS cannot be repeatedly assigned, but the elements of objects in JS can be repeatedly assigned.
  • throughObject.freeze()You can freeze objects, but only one layer. Multi-layer freezing requires manual recursive processing.

Deconstruction assignment

Array destruct assignment

// Array destruct
let [a, b, c] = [1.2.3];
console.log(a, b, c); / / 1, 2, 3

// Receive more parameters than array capacity
let [a, b, c, d] = [1.2.3];
console.log(a, b, c, d); // 1,2,3, undefined is equivalent to declaring no value

// Destruct the default assignment
let [a, b, c=1] = [1.2.3];
console.log(a, b, c); // There are corresponding elements in array 1,2, and 3. Default assignment is invalid so c = 3
Copy the code

Object destruct assignment

// Object destruct assignment
let { name, age } = { name: "A big fat man.".age: 10 };
console.log(name, age); // A big fat man, 10

// The field with more deconstructed elements than actual object elements is undefined
let { name, age, sex  } = { name: "A big fat man.".age: 10 };
console.log(name, age, sex); // a big fat, 10, undefined

// The default assignment object does not have the corresponding element, so age is still equal to 10
// Age equals 20 if the deconstructed object has no corresponding element
let { name, age = 20 } = { name: "A big fat man.".age: 10 };
console.log(name, age); // A big fat man, 10

// Destruct the alias
// The object element can be renamed during deconstruction, in which case the access name is equal to the empty string fullName
let { name:fullName, age } = { name: "A big fat man.".age: 10 };
console.log(name, age, fullName); // "", 10, "A fat man"
Copy the code

String destruct assignment

// String unpacking is basically the same as array unpacking
let [a,b,c] = '123'
console.log(a,b,c) / / 1, 2, 3
Copy the code

Extended operators (…)

  • If there is a duplicate between two objects, the one behind overwrites the one before.
  • MDN

An array of

  • Expand an array, or an array of classes, into comma-separated values.
  • Can be used to merge copy arrays and so on
let arr1 = [1.2.3.4.5.6]
console.log(... arr1)// 1 2 3 4 5 6

// Copy arrays to each other
let arr2 = [...arr1]
arr2.push(1)
console.log(arr2, arr1) // [1, 2, 3, 4, 5, 6, 1] [1, 2, 3, 4, 5, 6]

// Merge arrays
let arr3 = [3.4.5]
let arr4 = [...arr1, ...arr3]
console.log(arr4) // [1, 2, 3, 4, 5, 6, 3, 4, 5]
Copy the code

Object

  • Can be used for merge replicationObjectObject.
  • Show objects directly (. obj) throws an error!
let obj1 = {
  a: '1'.b: '2'.c: '3'
}

let obj2 = {
  b: '4'.a: '1'.c: '0'
}

// Duplicate key exists. Use the second parameter
letobj3 = {... obj1, ... obj2}console.log(obj3)  // { a: '1', b: '4', c: '0' }

// There is no duplicate value
letobj4 = {... obj1, ... obj2}console.log(obj4)  // { a: '1', b: '2', c: '3', d: '4', e: '1', f: '0' }

// The copied objects do not affect each other
letobj5 = {... obj1} obj5['b'] = '1111'
console.log(obj5, obj1)   // { a: '1', b: '1111', c: '3' } { a: '1', b: '2', c: '3' }

The rest of the argument must be at the end of the argument
const{a, ... res} = obj1console.log(a, res) // 1 {b: '2', c: '3'}
Copy the code

Array traversal method

Es5 array traversal method

The for loop

  • supportbreak continueKeyword can jump out early end loop
const arr = [1.2.3.4.5.1.1.2.3.4]

for (let i=0; i< arr.length; i++) {
    // Outputs the subscript with the corresponding value
  console.log(i, arr[i])
}
Copy the code

forEach

  • Does not supportbreak continueDo not jump out, do not prematurely end the loop
  • There is no return value, so noreturn
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
  • The third argument is a bit of a puzzle, and may be there to make it easier to get to the array itself in some cases
const arr = [1.2.3.4.5.1.1.2.3.4]
arr.forEach((item, index, arrs) = > {
  console.log(item, index, arrs)
})
Copy the code

map

  • If no data is returned, the elements of the returned value array areundefined
  • Returns a new array without changing the original array
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]

let ar = arr.map((item, index, arrs) = > {
  console.log(item, index, arrs)
  return ++item
})
console.log(ar)

Copy the code

Simulated Map method

  • Note the assignment to the array prototypeprototypePhi can’t be an arrow function, because the arrow functionthisThe point is not the caller.
const arr = [1.2.3.4.5.1.1.2.3.4]

Array.prototype.testMap = function(fn) {
  let index = 0,
  len = this.length
  res = new Array(len)

  while(++index < len) {
    res[index] = fn(this[index], index, this)}return res
}

arr.testMap(function(item, index) {
  console.log(item, index)
})
Copy the code

filter

  • Filter the data returned as true
  • You can return a value. If no data is returned, the array of returned values is an empty array
  • Returns a new array without changing the original array
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]

let ar = arr.filter((item, index) = > {
  console.log(item, index)
  return item === 1
})

console.log(arr, ar) // [1, 2, 3, 4, 5, 1, 1, 2, 3, 4]

Copy the code

some

  • Returns a Boolean value to iterate over whether there is any eligible data in the number group.
  • As long as one of them meets the criteria, it returnstrueOtherwise returnfalse
  • If no data is returned, the return value isfalse
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]

let ar = arr.some((item, index) = > {
  console.log(item, index)
  // return item === 1
})

console.log(arr, ar) // [ 1, 2, 3, 4, 5, 1, 1, 2, 3, 4 ] true
Copy the code

every

  • Returns a Boolean value to iterate over whether there is any eligible data in the number group.
  • As long as one does not meet the criteria, returnfalseOtherwise returntrue
  • If no data is returned, the return value isfalse
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]

let ar = arr.every((item, index) = > {
  console.log(item, index)
  return item === 1
})

console.log(arr, ar) // [ 1, 2, 3, 4, 5, 1, 1, 2, 3, 4 ] false
Copy the code

reduce

  • Accepts two parameter callback functions, initial values.
    • The callback function takes four arguments, the last callback value, the current element, the subscript, and the current array
  • This method is amazing, but I can’t use 😁 well and can’t remember the application scenario. Just a quick introduction. The big guy’s list of 25 advanced uses of Array Reduce that you need to know is worth a look.
  • The initial value, and the return value of the last callback function, are the two parameters that you understand how to use.
// The simplest example is array summation 😜
const arr = [1.2.3.4.5.1.1.2.3.4]

// Because it is summing up the initial value to give a 0
// pre is the return value of the last callback (equivalent to prefix and) cur is the current value added to the array is 1, 2, 3
// The first loop (0 is the initial value) 0 + 1 = 1
// Loop 1 + 2 = 3
// Loop 3 + 3 = 6 returns 6

let sum = arr.reduce((pre, cur, index, arr) = > {
  return pre + cur
},0)

console.log(arr, sum) // [1, 2, 3, 4, 5, 1, 1, 2, 3, 4] 26
Copy the code

for in

  • for inIt is theoretically possible to iterate over a set of numbers, but there are a few problems. It will iterate over methods that are custom defined on the prototype, but we don’t need it.
const arr = [1.2.3.4.5.1.1.2.3.4]

Array.prototype.testFor = function() {
  console.log('testFor')}for (let index in arr) {
 console.log(index, arr[index]) 
}
Copy the code

Es6 array traversal method

find

  • returnThe first oneA qualified value is returned if none existsundefined
  • If no data is returned, the return value isundefined
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]

let ar = arr.find((item, index, arrs) = > {
  return item === 2
})

console.log(ar) / / 2
Copy the code

findIndex

  • returnThe first oneThe subscript of the eligible value is returned if no eligible value existsundefined
  • If no data is returned, the return value isundefined
  • Takes three arguments to currently traverse the element, the subscript, and the array itself
const arr = [1.2.3.4.5.1.1.2.3.4]
let ar = arr.findIndex((item, index, arrs) = > {
  console.log(item, index, arrs)
  return item === 2
})

console.log(ar) / / 1
Copy the code

for of

  • Array traversal method, which provides three methods for traversing arrays,values keys entries
    • The value of each item in the values array, called by default
    • Keys subscript
    • The value of each entry with subscript is an array
for (let item of arr) {
  console.log(item)
}
/ / 1234511234

for (let item of arr.values()) {
  console.log(item)
}
// Output is the same as above

// keys output subscript
for (let item of arr.keys()) {
  console.log(item)
}
/ / 0123456789

for (let [index, item] of arr.entries()) {
  console.log(index, item)
}
Copy the code

Extension of arrays

Class array or pseudoarray

  • An array-like object that does not have the standard array methods aspush, but as iterables they can be iterated over like arrays. Common pseudo-array objects:
    • throughdocument.getElementByxxxThe obtained data IDS are excluded.HTMLCollection
    • throughdom.querySelectorAllThe data obtained.NodeList
    • Array parameter objectArguments
  • Create an array-like object or a pseudo-array object
let pseudoArray = {
  0: '1'.1: '2'.2: '3'.length: 3
}
Copy the code

Class array or pseudoarray to array

  • Class array object, class array to object
let pseudoArray = {
  0: '1'.1: '2'.2: '3'.length: 3} case1Through the array`slice`
let arr = [].slice.call(pseudoArray)
console.log(arr) / / / "1", "2", "3"]2Through the ES6 array method`from`
let arr = Array.from(pseudoArray)
console.log(arr) / / / "1", "2", "3"]
Copy the code
  • Class array to array (class array value array parameterArgumentsThrough thedocument.getElementByxxxData acquired, etc.)
// By expanding the operator
let divs = document.getElementsByTagName('div')
let arr = [...divs]
arr.push('1')

The // object.entries () method returns an array of key-value pairs for the given Object's own enumerable properties,
// Its arrangement and use for... The in loop returns the same order as it iterates through the object (the difference is that the for-In loop also enumerates properties in the prototype chain)
let arr1 = Object.entries(divs)
arr1.push('1')
Copy the code

Array.of

  • Array.of()Method creates a new array instance with a variable number of arguments, regardless of the number or type of arguments.
  • Array.of()ArrayThe difference between constructors is that they handle integer arguments:Array.of(7)Create an Array with a single element 7, and Array(7) creates an empty Array of length 7.empty) instead of being made up of 7undefinedArray).
// The number of parameters does not affect the array generated results are always consistent
Array.of(7);       / / [7]
Array.of(1.2.3); / / [1, 2, 3]

// The number of arguments affects the result of array generation
Array(7);          // [,,,,,,]
Array(1.2.3);    / / [1, 2, 3]
Copy the code

Array.copyWithin

  • copyWithin()Method shallowly copies part of an array to another location in the same array and returns it without changing the length of the original array.
  • copyWithinIs a mutable method, it doesn’t changethisThe length of thelengthBut it will changethisIts own content, and new properties are created as needed.
  • Take three parametersArray.copyWithin(target,start,end)
    • The parameters target, start, and end must be integers.
    • If start is negative, the specified index position is equal to length+start, where length is the length of the array. The same is true of end.
  • Ie does not support

// If it is negative, target will count from the end. Let's copy a few bits from a few
[1.2.3.4.5].copyWithin(-2)
// [1, 2, 3, 1, 2]

// 0 Copies data to position 0
// 3 is copied from index 3, since there is no end, to the end of the array, which is 45
// Copy two bits to replace two bits at 0
[1.2.3.4.5].copyWithin(0.3)
// [4, 5, 3, 4, 5]

// 0 Copies data to position 0
// 3 starts at index 3 and copies to index 4
[1.2.3.4.5].copyWithin(0.3.4)
// [4, 2, 3, 4, 5]

// The two bits from right to left of the array are subscript 4
// start copying the array from right to left with subscript 3
// -1 ends the copy array from right to left with the subscript 5
[1.2.3.4.5].copyWithin(-2, -3, -1)
// [1, 2, 3, 3, 4]
Copy the code

Array.fill

  • fill()Method populates an array with a fixed value from the start index to the end index. Does not include terminating indexes.
  • fill()A method is a mutable method, and it changes the one that called itthisObject itself, and return it instead of returning a copy.
  • Ie does not support
const array1 = [1.2.3.4];

// Fill positions 2 to 4 with 0
console.log(array1.fill(0.2.4));
// [1, 2, 0, 0]

// Fill 5 from position 1
console.log(array1.fill(5.1));
// [1, 5, 5, 5]

// If there is only one parameter, the entire contents of the array are populated with that parameter
console.log(array1.fill(6));
// [6, 6, 6, 6]

Copy the code

Array.includes

  • includes()The array () method checks whether an array contains a specified value, depending on the case, and returns if it doestrueOtherwise returnfalse.
  • includes()Comparing strings and characters is case sensitive.
  • The second parameter is optional and indicates the starting point for retrieval. The default value is 0, and a negative value is equal to its length + the second argument.
  • withindexOfThe method is similar, butindexOfUnable to determineNan.
  • Ie does not support
const array1 = [1.2.3];

console.log(array1.includes(2));
// true

const pets = ["cat"."Dog"."bat"];

console.log(pets.includes("dog"));
// false

console.log(pets.includes("cat"));
// true

console.log(pets.includes("at"));
// false
Copy the code

Array.flat

  • flat() Method recurses through an array of numbers at a specified depth and returns all elements in a new array combined with the elements in the traversed subarray.
  • flat()Method removes an empty item from the array.
  • Accepts an argument indicating that the level of amortization is 1 by default
var arr1 = [1.2[3.4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1.2[3.4[5.6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1.2[3.4[5.6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

// Use Infinity to expand nested arrays of any depth
var arr4 = [1.2[3.4[5.6[7.8[9.10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Remove an empty item from the array
var arr4 = [1.2.4.5];
arr4.flat();
// [1, 2, 4, 5]
Copy the code

Array.flatMap

  • flatMap() Method first maps each element using a mapping function, and then compresses the result into a new array.
  • Maybe it is more efficient to process two-dimensional arrays into one-dimensional arrays than map.
var arr1 = [1.2.3.4];

arr1.map(x= > [x * 2]);
[[2], [4], [6], [8]]

arr1.flatMap(x= > [x * 2]);
// [2, 4, 6, 8]

// only one level is flattened
arr1.flatMap(x= > [[x * 2]]);
[[2], [4], [6], [8]]
Copy the code

function

Parameters of a function

  • Function arguments cannot have the same name. An error will be thrown.
  • A variable with the same name as a function parameter cannot be declared inside a function. An error will be thrown.
  • The function argument is not passed yesundefined
function test (x,y) {
  console.log(x,y) // 1 undefined
}
test(1)
Copy the code

The default argument to the function

  • The default parameter is not transmitted. Passed is passed value
  • Place the default argument at the end of the function argument. You’ll see why.
// Do not pass the default parameters
function test (x,y=2) {
  console.log(x,y) / / 1. 2
}
test(1)

// Pass default arguments
function test (x,y=2) {
  console.log(x,y) / / 1 3
}
test(1.3)
Copy the code

Function arguments are combined with deconstruction when they are objects

  • When the function argument is an object, the argument that does not exist after deconstruction isundefinedCase 1,
  • If the function argument is an object and the argument is destructed, an error will be thrown if no argument is passed, as shown in Example 2
  • The solution to the error in example 2 is to assign an empty object (default argument) by default in example 3
// 例1
function test ({x=1, y}) {
  console.log(x,y) // 1 undefined
}
test({})

// 例2
function test ({x=1, y}) {
  console.log(x,y) 
}
test()

// 例3
function test ({x=1, y} = {}) {
  console.log(x,y) // 1 undefined
}
test()

Copy the code

Function of the length

  • Function of thelengthIs the number of arguments.
  • From the first parameter to the first parameter specifying the default parameter if no default parameter is specified, the sum of the total number of parameters
  • Does not contain the number of parameters that specify the default parameter, if the first parameter specifies the default parameterlength = 0
function test(a = 1, b, c, d) {}
console.log(test.length) / / 0

function test(a, b = 1, c, d) {}
console.log(test.length) / / 1

function test(a, b, c, d) {}
console.log(test.length) / / 4
Copy the code

Function parameter scope

  • Function parameters have scope
// The parameter itself has a scope. The scope variable is preferred (each parameter is equivalent to one variable)
let a = 1;
function test(a, b = a) {
  console.log(a, b); / / 1 1
}

test(3);

// If the parameter does not exist in the parameter scope, the search is up, if the variable does not exist, an error is thrown.
let x = 1;
function test(a, b = x) {

  let x = 3;
  console.log(a, b); // undefined 1
}

test();

Copy the code

The function name

  • The named function name is the function name, and the anonymous function isanonymous
function test() {}
console.log(test.name) // test

console.log((new Function).name) // anonymous
Copy the code

Rest parameters

  • Rest arguments, the rest argument syntax allows us to represent an indefinite number of arguments as an array.
  • If the last named parameter of the function is.Is prefixed, then it becomes a true array of remaining arguments, where the values from 0 (including)res.lengthThe (excluded) element is supplied by the actual argument passed to the function.
// When the parameters passed are not correct
function test (. res) {
  console.log(res) // [1, 2, 3, 4]
}

test(1.2.3.4)

// Some parameters are known to have uncertain parameters
function test (a, ... res) {
  console.log(a,res) // 1 [2, 3, 4]
}

test(1.2.3.4)
Copy the code

Arrow function

  • Arrow functions don’t have their ownthis. The arrow function captures its contextthisValue, as its ownthisValue.
  • Arrow functionthisThe immutable.Call (), apply(), bind()These methods do not change the arrow functionthisPointing to.
  • Arrow function not availablenewKeyword to instantiate the object, otherwise an error will be reported.
  • Arrow function doesn’t have anyargumentsObject.
  • grammar() = > {}
const getData = () = > {
    return 'abc'
}
Copy the code

Object extension

Kv of the same object can be abbreviated

let name = 'Big Brother Zhang'
let data = {name: name}

// Can be abbreviated as
let data = {name}
Copy the code
  • The variable is required as k of the object[]Such aslet data = {[name]: '1234'}

Functions in objects

// Use this to get the object itself. Arrow functions cannot be used
let data = {
    geName(){
        // Function logic
        console.log(this)}}Copy the code

Object.is

  • Object.is()Used to determine whether two values are exactly equal, but equal to= = =There are differences, such asObject.is(NaN,NaN)returntrue= = =returnfalse.
  • mdn Object.is

inUsed to determine whether an object has a key and returns a Boolean value.

let c = {a:1.b:2}
console.log('c' in c) // false
console.log('a' in c) // true
Copy the code

Object traversal

let data = {a:1.b:2}

for (item in data) {
    console.log(item) // a, b
}

Object.keys(data) // ['a' , 'b']

Object.values(data) / / [1, 2]

Object.getOwnPropertyNames(data) // ["a", "b"]

Reflect.ownKeys(data) // ["a", "b"]
Copy the code

Object.keys

  • Object.keys()Method returns an array of a given object’s own enumerable properties in the same order as they would be returned if the object were iterated through normally.
var arr = ['a'.'b'.'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

var obj = { 0: 'a'.1: 'b'.2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
Copy the code
  • Note that in ES5, if the argument to this method is not an object (but a primitive value), it raises TypeError. In ES2015, non-object parameters are cast to an object.
Object.keys("foo");
// TypeError: "foo" is not an object (ES5 code)

Object.keys("foo");
// ["0", "1", "2"] (ES2015 code)
Copy the code

Object.values

  • Object.values()Method returns an array of all enumerable property values for a given object itself.
var obj = { foo: 'bar'.baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

var obj = { 0: 'a'.1: 'b'.2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']
Copy the code

Object.entries

  • Object.entries()Method returns an array of key-value pairs for the given object’s own enumerable properties.
const obj = { foo: 'bar'.baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

const obj = { 0: 'a'.1: 'b'.2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
Copy the code

Object.fromEntries

  • Object.fromEntries() Method converts a list of key-value pairs to an object.
  • serializationObject.entriesFor the object
/ / map obj
const map = new Map([['foo'.'bar'], ['baz'.42]]);const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }

// convert k v array to obj
const arr = [ ['0'.'a'], ['1'.'b'], ['2'.'c']].const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
Copy the code

Descriptor Object. GetOwnPropertyDescriptors attribute

  • Object.getOwnPropertyDescriptors() The getDescriptor () method is used to get the descriptors of all of an object’s own properties.
  • Descriptor for all of the specified object’s own properties, or returns an empty object if there are none.

  • valueObject field value
  • configurableWhether the property description of an object can be changed or whether the property can be deleted
  • enumerableWhether it can be enumerated
  • writableWhether the value of the property can be changed
// The value of writable is false and cannot be modified
const obj = {}
Reflect.defineProperty(obj, 'name', {
    value: 'xiaoliu'.writable: false.configurable: true.enumerable: true
})
obj.name = 'xiahua'
console.log(obj)

// Signals are false and cannot be deleted
const obj = {}
Reflect.defineProperty(obj, 'name', {
    value: 'xiaoliu'.writable: true.configurable: false.enumerable: true
})
delete obj.name
console.log(obj)

// Enumerable is false and cannot be enumerable
const obj = {}
Reflect.defineProperty(obj, 'name', {
    value: 'xiaoliu'.writable: true.configurable: true.enumerable: false
})
for(let key in obj){
    console.log(key)
}
Copy the code

Deep copy and shallow copy

  • Both deep and shallow copies are for reference data types only.
    • Shallow copy copies the object member by member, but only the memory address is copied, not the object itself. The old and new object members still share the same memory.
    • Deep copy creates an identical object. The new object does not share memory with the original object, and changes to the new object will not change to the original object.
  • Difference: Shallow copy copies only the first layer properties of an object, while deep copy copies the properties recursively.

Shallow copy

Object.assign

  • Object.assignMethod is used to assign the values of all enumerable attributes from one or more source objects to the target object. It will return the target object.
  • Object.assignMethod copies only the enumerable properties of the source object itself to the target object.
  • Pay attention to,Object.assignNot in thosesourceObject value isnull 或 undefinedThrows an error.
const target = { a: 1.b: 2 };
const source = { b: 4.c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
Copy the code

Deep copy

JSON.parse(JSON.stringify())

  • Convert the object to a string with json.stringify () (the reference datatype is changed to a primitive datatype so there is no reference relationship), and parse the string into an object with json.parse ().
  • Note: json.stringify () has some problems converting data please specifyRefer to the description of MDN json.stringify ()
let data = [1.2.3.4]
let data2 = JSON.parse(JSON.stringify(data))
data.push(5)
console.log(data2)
/ / [1, 2, 3, 4]
Copy the code

Of course, this is just a primer, on the deep copy of shallow copy of the article, there are many examples. Libraries are a good way to use them properly, for examplelodash.

Classes and inheritance in ES5

Define class attributes and methods

// Define a class
function Person(name, age) {
    // Example properties
    this.name = name;
    this.age = age;  
}

Static attributes can be used without instantiation
Person.a = '1111111111111'
console.log(Person.a);

// Static method
Person.log = function (info) {
    // The static method's this refers to the class so we can't get this.name
    console.log(info)
}
Person.log('This is a log 111111111111111111')


// Add a prototype method
Person.prototype.logInfo = function () {
    console.log("Name:".this.name, "Age.".this.age);
};

// instantiate the object
let p1 = new Person("xiaoliu"."18");
p1.logInfo();
Copy the code

Class inheritance

/ / parent class
function Animal(name) {
    this.name = name
}
Animal.prototype.showName = function () {
    console.log('The name is :' + this.name)
}

/ / subclass
function Dog(name, color) {
    // Inherit attributes
    Animal.call(this, name) 
    this.color = color
}

// Inherits the parent method
Dog.prototype = new Animal()
Dog.prototype.constuctor = Dog

let d1 = new Dog('xiaoliu'.'orange')
console.log(d1)
d1.showName()

Copy the code

Classes and inheritance in ES6

Define a class class

The class keyword defines a class
class Person {
    // Instance properties
    constructor(name, age) {
      this.name = name;
      this.age = age;
    }

    logName() {
      console.log("Output name:".this.name);
    }

    // Currently class does not support defining static attributes
    // But it is proposed that static attributes be defined by static a = 1

    // Static method
    static logAge(age) {
      console.log("Output age:", age); }}Static methods are similar to es5 implementations
Person.a = '111111111'
console.log( Person.a)

let p1 = new Person("xiaoliu"."19");
p1.logName();
Person.logAge(p1.age);
Copy the code

Class inheritance

// Inherits the Person parent class
class Man extends Person {
    constructor(name, age, sex) {
      // Instance attributes name, age inherit from the Person parent class
      super(name, age);
      // Sex is the attribute of the Man instance
      this.sex = sex;
    }

    logSex() {
      console.log("Gender:.this.sex); }}let M1 = new Man("xiaozhang"."20"."man");
M1.logName();
M1.logSex();
Man.logAge(M1.age);
Copy the code

New data types

BigInt Specifies the original data type

  • BigIntIs a built-in object that can represent arbitrarily large integers. It provides a way to say greater than253-1The integer.
  • defineBigIntAdd after an integer literalnSuch as:10nOr call a functionBigInt().
  • When usingBigIntWhen, operations with decimals are rounded.
  • BigIntValue to useJSON.stringify()Can triggerTypeErrorBecause by defaultBigIntValues are not inJSONSerialize. This can be done manually if necessarytoJSONMethods.
  • BigIntIn some waysNumber, but there are a few key differences:
    • Cannot be used forMathObject.
    • Not with anyoneNumberInstances are mixed; both must be converted to the same type.
    • Be careful when converting back and forth between two types, becauseBigIntThe variable is being converted toNumberVariable may lose precision.
const theBiggestInt = 9007199254740991n;
const alsoHuge = BigInt(9007199254740991);
Copy the code

The original data type Symbol

  • symbolIs a basic data type
  • Symbol()The function returnssymbolType that has static properties and static methods. Its static attributes expose several built-in member objects; Its static method exposes the global Symbol register and is similar to the built-in object class, but as a constructor it is incomplete because it does not support syntax:”new Symbol()“.
  • Each fromSymbol()The returned symbol value is unique. A symbol value can be used as an identifier for object properties;
  • Accepts one argument, of type string. A description of a symbol that can be used to debug but not access the symbol itself.Symbol('foo');
var sym1 = Symbol(a);var sym2 = Symbol('foo');
var sym3 = Symbol('foo');
Copy the code
  • Pay attention to.Symbol("foo")The string “foo” is not forced to be converted to symbol. It creates a new symbol type each time:
Symbol("foo") = = =Symbol("foo"); // false
Copy the code

Data structure Set

  • SetObjects allow you to store a unique value of any type, either a primitive value or an object reference.
  • addSetAdds an element to the end of the object. Returns theSetObject.
  • deleteremoveSetReturns a Boolean value for the element equal to the value in.
  • clear()removeSetAll elements within the object.
  • sizeReturns the set length.
  • hasReturns a Boolean value indicating that the value is inSetExists or not.
  • entries,keys,valuesAll return an iterable.
let mySet = new Set(a); mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add("some text"); // Set [ 1, 5, "some text" ]
let o = {a: 1.b: 2};
mySet.add(o);

mySet.add({a: 1.b: 2}); // o points to a different object, so no problem

mySet.has(1); // true
mySet.has(3); // false
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has("Some Text".toLowerCase()); // true
mySet.has(o); // true

mySet.size; / / 5

mySet.delete(5);  // true to remove 5 from set
mySet.has(5);     // false, 5 has been removed

mySet.size; // 4, just removed a value

// Iterate through the set
/ / output in sequence: 1, the text ", "{" a" : 1, "b", 2}, {" a ": 1," b ": 2}
for (let item of mySet) console.log(item);
Copy the code

WeakSet

  • WeakSetCan only beCollection of objects, and cannot be any value of any type. Traversal is not supported (it can be made iterative by adding the iterator protocol).
  • WeakSetObject allows you to store weakly held objects in a collection.
  • If you pass in aiterableAs arguments, all iteration values for the object are automatically added to the generatedWeakSetIn the object.nullIs considered to beundefined.
var ws = new WeakSet(a);var foo = {};
var bar = {};

ws.add(foo);
ws.add(bar);

ws.has(foo);    // true
ws.has(bar);   // true

ws.delete(foo); // Delete foo from set
ws.has(foo);    // false, the foo object has been deleted
ws.has(bar);    // true, bar still exists
Copy the code
  • Pay attention to,foo ! == bar. Although they are similar objects, they are notSame object. Therefore, they can all be added to the set.

Data structure Map

  • MapThe object holds key-value pairs and can remember the original insertion order of the keys. Any value can be a key or a value.
  • setMapAdds a key-value pair to the end of the object.
  • getTo obtainMapObject key value pairs. There is no returnundefined
  • deleteremoveMapReturns a Boolean value for the element equal to the value in.
  • clear()removeMapAll elements within the object.
  • sizeReturns the Map length.
  • hasReturns a Boolean value indicating that the value is inMapExists or not.
  • entries,keys,valuesAll return an iterable.
let myMap = new Map(a);let keyObj = {};
let keyFunc = function() {};
let keyString = 'a string';

/ / add the key
myMap.set(keyString, "Value associated with key 'a string'");
myMap.set(keyObj, "Value associated with keyObj");
myMap.set(keyFunc, "Value associated with keyFunc");

myMap.size; / / 3

/ / read the values
myMap.get(keyString);    // "Value associated with key 'a string'"
myMap.get(keyObj);       // "Value associated with keyObj"
myMap.get(keyFunc);      // "Value associated with keyFunc"

myMap.get('a string');   // "Value associated with key 'a string'"
                         // Because keyString === 'a string'
myMap.get({});           // undefined because keyObj! = = {}
myMap.get(function() {}); // undefined because keyFunc! == function () {}
Copy the code
  • MapYou can usefor.. ofLoop to achieve iteration:
let myMap = new Map(a); myMap.set(0."zero");
myMap.set(1."one");
for (let [key, value] of myMap) {
  console.log(key + "=" + value);
}
// Two logs will be displayed. One is "0 = zero" and one is "1 = one"

for (let key of myMap.keys()) {
  console.log(key);
}
// Two logs will be displayed. One is zero and the other is one.

for (let value of myMap.values()) {
  console.log(value);
}
// Two logs will be displayed. One is "zero" and the other is "one"

for (let [key, value] of myMap.entries()) {
  console.log(key + "=" + value);
}
// Two logs will be displayed. One is "0 = zero" and one is "1 = one"
Copy the code

WeakMap

  • Traversal is not supported
  • WeakMapAn object is a collection of key/value pairs whose keys are weakly referenced. Its key must be an object (ObjectType,SymbolNo), and the value can be arbitrary.
const wm1 = new WeakMap(),
      wm2 = new WeakMap(),
      wm3 = new WeakMap(a);const o1 = {},
      o2 = function(){},
      o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // Value can be any value, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // Keys and values can be any object, even another WeakMap object

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined,wm2 has no o2 key
wm2.get(o3); // undefined, undefined

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if undefined)

wm3.set(o1, 37);
wm3.get(o1); / / 37

wm1.has(o1);   // true
wm1.delete(o1);
wm1.has(o1);   // false
Copy the code
  • Implement some map methods
class ClearableWeakMap {
  constructor(init) {
    this._wm = new WeakMap(init)
  }
  clear() {
    this._wm = new WeakMap()}delete(k) {
    return this._wm.delete(k)
  }
  get(k) {
    return this._wm.get(k)
  }
  has(k) {
    return this._wm.has(k)
  }
  set(k, v) {
    this._wm.set(k, v)
    return this}}Copy the code

String extension

Unicode representation of characters

  • Place code points in {} so that they are not restricted by the maximum FFFF of unicode code points
console.log('\u20bb7') // ₻7 parses the output ₻ and 7 separately
console.log('\u{20bb7}') / / 𠮷
Copy the code

String traversal for of

let str = 'pikaqiu-'

for (item of str) {
    console.log(item)
}
Copy the code

Template string

let str = "Chuheridangwu \r\n" + "Sweat drops to the ground."

// Use backquotes to preserve the text format as STR output
let str1 = Hoe Heridangwu, sweat drops wo soil. `

// Dynamic characters
let num = 1
let str2 = ` weeks today${num}`
console.log(str2) // Today is Monday
Copy the code

Tagged template string

function foo (a,b,c,d) {
    console.log(a)
    console.log(b)
    console.log(c)
    console.log(d)
}

const num1 = '十八'
const num2 = '二'
const num3 = 'Second year'
const num4 = '一'
fooI this year `${num1}Years old, read${num2}Grade, in${num3}${num4}Class `
Copy the code

fromCodePoint

  • Converting Unicode encoding
// Es5 yards cannot exceed FFFF
String.fromCharCode(0x20bb7) / / ஷ
// Es6 has no upper limit
String.fromCodePoint(0x20bb7) / / 𠮷
Copy the code

includes

  • Returns a Boolean value for whether the string contains the specified characters
let str = 'pikaqiu'
console.log(str.includes('pi')) // true
Copy the code

StartsWith and endsWith

  • startsWith()The method is used to determine whether the current string begins with another given substring and returns based on the resulttrue 或 false.
  • endsWith() The getString () method checks whether the current string is “terminated” by another given substring, and returns based on the resulttrue 或 false.
let str = 'pikaqiu'
console.log(str.startsWith('pi')) // true
console.log(str.endsWith('iu')) // true
Copy the code

PadStart and padEnd

  • The two methods are defined inString.prototypeInstance methods
  • padStart()Method populates the current string with another string (repeated multiple times if necessary) so that the resulting string reaches a given length. Starts at the beginning of the current string.
  • padEnd()Method populates the current string with a string (repeated if necessary) and returns the string that has been populated to the specified length. Padding starts at the end of the current string.
  • The target length for the current string padding. If less than the length of the current string, the current string itself is returned. (String length 3 padding <= 3 returns the string itself)
let te = 'xxx'
console.log(te.padStart(5.'y')) // yyxxx
console.log(te.padEnd(5.'y')) // xxxyy
Copy the code

repeat

  • repeat()Constructs and returns a new string containing a specified number of copies of the strings concatenated together.
  • The number of repetitions cannot be negative.
  • The number of repetitions must be less than infinity and no longer than the longest string.
let str = 'pikaqiu-'
// 10 indicates the number of repetitions
console.log(str.repeat(10)) 
// pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-pikaqiu-
Copy the code

TrimStart, trimEnd trimLeft, and trimRight

  • trim()Remove space before and after
  • trimStart()Method to remove a space from the beginning of a string.trimLeft()Is an alias for this method.
  • trimEnd()  Removes whitespace from the end of a string.trimRight()Is the alias of this method.
const greeting = ' Hello world! ';
console.log('trimStart',greeting.trimStart())
console.log('trimEnd',greeting.trimEnd())
console.log('trimLeft',greeting.trimLeft())
console.log('trimRight',greeting.trimRight())
Copy the code

String.matchAll

  • matchAll()Method returns an iterator containing the results of all matching regular expressions and a grouping capture group.
  • If the passed parameter is not a regular expression object, it is used implicitlynew RegExp(obj)Convert it to oneRegExp.
  • RegExpGlobal mode must be setgOtherwise an exception will be thrownTypeError.
var regexp = /t(e)(st(\d?) )/g;
var str = 'test1test2';

str.match(regexp);
// Array ['test1', 'test2']



let array = [...str.matchAll(regexp)];
array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]

Copy the code

Regular expression extensions

Y modifier

  • yThe first remaining adhesive modifier starts matching,gThe global matching
 let str = 'eee-e-ee-eee-ee'
let reg = /e+/y // The first remaining modifier starts matching

// Search from the starting position
console.log(reg.exec(str)) // eee
// The match starts from the first after the eEE. If no match is found, null is returned
console.log(reg.exec(str)) // null
// Start matching from scratch
console.log(reg.exec(str)) // eee
Copy the code

U modifier

  • The modifieruProvide Unicode support in regular expressions.
  • Four-byte characters are treated the right way: as a single character, not as two 2-byte characters.
  • unicodeCode point range\u0000~\uffff

const str = '\uD842\uDFB7' // Represents a character
console.log(/^\uD842/.test(str)) // ES5 true does not recognize Unicode encoding matches correctly
console.log(/^\uD842/u.test(str)) // es6 false

//. Any single character except newline
console.log($/ / ^.test(str)) // false
console.log(/^.$/u.test(str)) // true

console.log(/\u{61}/.test('a')) // false
console.log(/\u{61}/u.test('a')) // true

console.log(/ 𠮷 {2} /.test('𠮷 𠮷')) // false
console.log(/ 𠮷 {2} / u.test('𠮷 𠮷')) // true
Copy the code

S modifier

  • dotAllAttribute indicates whether they are used together in regular expressions.”s“Modifier (introduces the /s modifier so that. Can match any single character).dotAllIs a read-only property that belongs to a single regular expression instance.

Named Group matching

  • Provide a name for the group
const reg = / (? 
      
       \d{4})-(? 
       
        \d{2})-(? 
        
         \d{2})/
        
       
      
console.log(reg.exec('2021-10-09'))
const groups = reg.exec('2021-10-09').groups
console.log(groups)
Copy the code

After assertion

  • Matches a string ending in XXX and beginning with or without XXX
const str = 'ecmascript'
// predicate first
console.log('Predicate matches beginning with ECMA and ending with script',str.match(/ecma(? =script)/))
console.log('Predicate matches beginning with ECMA, not ending with script',str.match(/ecma(? =! script)/))
// es9 follows assertion
console.log('Final assertion match ends with script and begins with ecma',str.match(/ (? <=ecma)script/))
console.log('Final assertion match ends with script, not ecMA',str.match(/ (? 
      ))
Copy the code

Numerical extension

Into the system

  • 0BBinary at the beginning0OThe beginning indicates octal
// Decimal -> binary
const a = 5 / / 101
console.log(a.toString(2))

// Binary -> decimal
const b = 101
console.log(parseInt(b, 2))
Copy the code

Number.isFinite

  • Number.isFinite()The method is used to check if the parameter passed is a finite number.
  • With the globalisFinite()This method does not force a non-numeric parameter to be converted to a numeric value, which means that only values of numeric type, finite, are returnedtrue.
console.log(Number.isFinite(5)) // true
console.log(Number.isFinite(0.5)) // true
console.log(Number.isFinite(Infinity)) // false
console.log(Number.isFinite('asjdajkla')) // false
console.log(Number.isFinite(true)) // false
Copy the code

Number.isNaN

  • Number.isNaN()Method to determine whether the value passed isNaNAnd check whether the type isNumber. It’s the original globalisNaN()A more secure version of.
  • And global functionsisNaN()Compared to theNumber.isNaN()Does not convert a parameter to a number itself, only if the parameter is a value ofNaNIs returnedtrue.
console.log(Number.isNaN(NaN)) // true
console.log(Number.isNaN(15)) // false
Copy the code

Number.isInteger

  • Number.isInteger()The method is used to determine whether a given parameter is an integer.
  • Returns if the detected value is an integertrueOtherwise returnfalse. Pay attention toNaNAnd the positive and negativeInfinityNot an integer.
Number.isInteger(0);         // true
Number.isInteger(1);         // true
Number.isInteger(-100000);   // true

Number.isInteger(0.1);       // false
Number.isInteger(Math.PI);   // false

Number.isInteger(Infinity);  // false
Number.isInteger(-Infinity); // false
Number.isInteger("10");      // false
Number.isInteger(true);      // false
Number.isInteger(false);     // false
Number.isInteger([1]);       // false
Copy the code

Math.trunc

  • Math.trunc() Method will remove the decimal part of the number, justdeleteDiscard the decimal part and decimal point of a number, regardless of whether the argument is positive or negative. Keep only the integer part.
  • Arguments passed into the method are implicitly converted to numeric types.
Math.trunc(13.37)    / / 13
Math.trunc(42.84)    / / 42
Math.trunc(0.123)    //  0
Math.trunc(-0.123)   / / - 0
Math.trunc("1.123") // -1
Math.trunc(NaN)      // NaN
Math.trunc("foo")    // NaN
Math.trunc()         // NaN
Copy the code

`Math.sign

  • Math.sign()The function returns the symbol of a number indicating whether it is positive, negative, or zero.
  • The parameter passed in is implicitly converted to a numeric type.
  • The function returns 5 values: 1, -1, 0, -0, NaN. They are positive, negative, positive zero, negative zero, NaN.
Math.sign(3);     //  1
Math.sign(-3);    // -1
Math.sign("- 3");  // -1
Math.sign(0);     //  0
Math.sign(-0);    / / - 0
Math.sign(NaN);   // NaN
Math.sign("foo"); // NaN
Math.sign();      // NaN
Copy the code

The idempotent operator **

  • Exponentiation operator (**) returns the result of adding the first operand to the power of the second. It is equivalent toMath.pow, the difference is that it also accepts BigInts as its operand.
2 ** 3   / / 8
3 ** 2   / / 9
3 ** 2.5 / / 15.588457268119896
10* * -1 / / 0.1
NaN ** 2 // NaN
Copy the code

Proxy

  • ProxyObject is used to create a proxy for an object that intercepts and customizes basic operations (such as property lookup, assignment, enumeration, function calls, and so on).
  • grammarconst p = new Proxy(target, handler)
  • Take two parameterstargetProxy object,handlerObject is a placeholder object that holds a set of specific properties. It contains aProxyThe various traps of the. All catchers are optional. If a catcher is not defined, the default behavior of the source object is retained.

Commonly used method

  • getThe catcher for the property read operation.
  • setProperty set the catcher for the operation.
  • has inOperator.
  • deletePropertyDeletes the catcher for the operation.
  • ownKeys Object.getOwnPropertyNamesMethods andObject.getOwnPropertySymbolsMethod.
  • applyA catcher for a function call operation.
  • construct newOperator.

Get set trap example

const handler = {
    get: function (obj, prop) {
      // The default return value is 37 when no attribute name exists in the object.
      return prop in obj ? obj[prop] : 37;
    },
    set: function (obj, prop, value) {
      // The assignment field equals age
      if (prop === "age") {
        // Is an integer
        if (!Number.isInteger(value)) {
          throw new TypeError("The age is not an integer");
        }
        / / is more than 200
        if (value > 200) {
          throw new RangeError("The age seems invalid"); }}// Assign a value to the object
      obj[prop] = value;

      // A Boolean value is required to indicate success
      return true; }};const p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log("c" in p, p.c); // false, 37 is returned by default if field C does not exist

p.age = 100
console.log('age', p.age); // age 100 is correctly assigned

p.age = 300
console.log('age1', p.age); // The age seems invalid throws an error
Copy the code

Reflect the reflection

  • Reflection refers to the ability of a program to retrieve information about itself at runtime
  • ReflecT is a built-in object that provides methods to interceptJavaScriptIn the operation.ReflectIt’s not a function object, so it’s unconstructible, which means it’s not a constructor that you can’t passnewOperator to create or call it as a functionReflectObject.ReflectAll properties and methods of the.
  • The Reflect object has some methods andObjectSame, but there’s something in betweenSome subtle differences .
  • Modify someObjectTo make it reasonable.
  • letObjectOperations become functional behavior.
  • ReflectProxyThe method of one-to-one correspondence.
// Checks whether an object has a specific attribute
const duck = {
  name: 'Maurice'.color: 'white'.greeting: function() {
    console.log(`Quaaaack! My name is The ${this.name}`); }}Reflect.has(duck, 'color');
// true
Reflect.has(duck, 'haircut');
// false

// Returns a property of the object itself
Reflect.ownKeys(duck);
// [ "name", "color", "greeting" ]

// Add an attribute to the object
Reflect.set(duck, 'eyes'.'black');
// returns "true" if successful
// "duck" now contains the property "eyes: 'black'"
Copy the code

See this article for more examples and why Reflect is used

Promise

  • PromiseThe object represents the final completion (or failure) of an asynchronous operation and its resulting value.
  • aPromiseMust be in one of the following states and:
    • Pending: The initial state that has neither been granted nor rejected.
    • This is a big pity: this will be fulfilled successfully.
    • Rejected: Indicates that the operation fails.
  • Success or failure cannot be changed once determined

Then, the catch

new Promise((resolve, reject) = >{
  // resolve reject returns only one
  resolve('success! ')
  reject('failure! ')
})
.then(res= > {
  // Resolve returns the value here
  console.log('then', res)
})
.catch(err= > {
  // reject returns the value here
  console.log('catch', res)
})
Copy the code

finally

  • finally() Method returns aPromiseAt the end of the promise, whatever the outcomefulfilledOr is itrejectedExecutes the specified callback function.
  • Avoids the same statements needed inthen()andcatch()In each case.
const testPromise = new Promise((resolve, reject) = >{
  // resolve reject returns only one
  resolve('success! ')
  reject('failure! ')
})
.finally(() = > {
  / / resolve | | reject will trigger here
  console.log('finally')})console.log(await testPromise)
Copy the code

Promise.reject Static methods

  • Promise.resolve(value)Method returns a parsed value ofPromiseObject.
  • Warning: Do not call on Thenable that resolves to itselfPromise.resolve. This will result in infinite recursion as it tries to flatten the infinitely nestedpromise.
Promise.resolve("Success").then(function(value) {
  console.log(value); // "Success"
}, function(value) {
  // will not be called
});
Copy the code

Promise.resolve static method

  • Promise.reject() Method returns an object with a rejection reasonPromiseObject.
Promise.reject(new Error('fail')).then(function() {
  // not called
}, function(error) {
  console.error(error); // Stacktrace
});
Copy the code

Promise.all Static methods

  • Promise.all()Method receives apromise可迭代Iterable (Array, Map, and Set are ES6 iterable). Returns apromiseThe instance
  • All of the parameterspromiseWhen executed, an array of results is returned.
  • As long as any inputpromiserejectThe callback execution or input is invalidpromiseIt immediately throws an error,And rejectIs the first error message thrown.
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) = > {
  setTimeout(resolve, 100.'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) = > {
  console.log(values);
});
// expected output: Array [3, 42, "foo"]
Copy the code

Promise.allSettled

  • Promise.allSettled() The method returns a value that all given promises havefulfilledorrejectedAfter the promise, with an array of objects, each representing the corresponding promise result.
  • In layman’s terms, the result of an argument in which a promise is fully executed does not care whether it succeeds or fails
const promiseList = [
  Promise.resolve({
    code: 200.data: [1.2.3],}).Promise.reject({
    code: 500.data: []}),Promise.resolve({
    code: 200.data: [7.8.9],}),];Promise.allSettled(promiseList)
  .then((res) = > {
    console.log("Success", res);
  })
  .catch((err) = > {
    console.log("Failure", err);
  });
Copy the code

Generator Generator object

  • The Generator Generator object consists of the following parts
    • function*This declaration (functionThe keyword followed by an asterisk) defines oneGenerator function(Generator function), which returns aGeneratorObject.
    • Iterable protocolAllows JavaScript objects to define or customize their iterative behavior to beCan the iterationObject, an object must be implemented @@iteratorMethods. That is, there is a key on the prototype[Symbol.iterator]
    • Iterator protocolDefines a standard way to produce a series of values, whether finite or infinite. When a finite number of values are iterated over, a default return value is returned.
    • MDN iterative protocol, Generator Function
function *gen(){
    yield 10;
    x=yield 'foo';
    yield x;
}

var gen_obj=gen();
console.log(gen_obj.next());// execute yield 10 to return 10
console.log(gen_obj.next());// perform yield 'foo' and return 'foo'
console.log(gen_obj.next(100));// assign 100 to the lvalue of the previous yield 'foo', that is, execute x=100 and return 100
console.log(gen_obj.next());// Value is undefined and done is true
Copy the code
  • When explicit in a generator functionreturn Causes the generator to immediately go to the finished state, which is callednext()The object returned by thedone fortrue. ifreturn If it’s followed by a value, then that value will beThe currentcallnext()The value returned by the method.
  • You can think of it as a function that you can control because it’s callednext()Will continue to execute (honestly this paragraph is written indeed water 😪).

The module module

  • The importimportexportexport default || export
  • export defaultThere can only be one,exportYou can have multiple. You can have both at the same time.
  • export defaultMust be defined before use.

Export keyword

// Export one
export const a = 5

// Export multiple
export const a = 5
export const b = '123456'
// Export an object directly
export {
    a,
    b
}
Copy the code

Export default keyword

// Export one
const a = 5
export default a
// Export default 5

// Export multiple
const a = 5
const b = '123456'
export default {
    a,
    b
}

Copy the code

The import import

  • ./moduleTo export files
// export Import names must be the same
import { a, b } from './module'

// export default import The mod is the exported object if it is exported
{a:5, b: '123456'}
import mod from './module'
Copy the code

Dynamic import

  • The keyword import can be used to dynamically import modules as if they were functions. Called this way, one is returnedpromise.
  • Do not abuse dynamic imports (only when necessary). Static frameworks are better at initializing dependencies and are better for static analysis tools and toolstree shakingPlay a role
  • supportawaitThe keyword.
import('/modules/my-module.js')
  .then((module) = > {
    // Do something with the module.
  });

// 'await' keyword.
let module = await import('/modules/my-module.js');
Copy the code

Import the alias as keyword

// export import rename a to AA
import { a as aa, b } from './module'


// export default import rename to mod
import * as mod from './module'
Copy the code

Mixed import/Export

// Two types of export
export const name = 'xiaohu'

const a = 5
export default a

// Two types of imports
import mod, { name } from './module'
Copy the code

Async and await

  • asyncThe keyword is placed before the function to make itAn asynchronous functionReturns apromiseobject
  • awaitKeyword callAn asynchronous functionExecute them synchronously

Rewrite the Promise code with async/await

fetch('coffee.jpg')
.then(response= > response.blob())
.then(myBlob= > {
  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
})
.catch(e= > {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});
Copy the code
async function myFetch() {
  let response = await fetch('coffee.jpg');
  let myBlob = await response.blob();

  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}

myFetch()
.catch(e= > {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});
Copy the code

Error handlingtry... catch

async function myFetch() {
  try {
    let response = await fetch('coffee.jpg');
    let myBlob = await response.blob();

    let objectURL = URL.createObjectURL(myBlob);
    let image = document.createElement('img');
    image.src = objectURL;
    document.body.appendChild(image);
  } catch(e) {
    console.log(e);
  }
}

myFetch();
Copy the code

for await… Of asynchronous iterator

  • for await... ofStatement creates a loop that iterates over both asynchronous and synchronous iterables.
  • Can only be used inside an async function.
  • for await... ofDoes not apply to asynchronous iterators that are not asynchronously iterable.
  • Symbol.asyncIteratorThe symbol specifies the default asynchronous iterator for an object. If an object has this property set, it is an asynchronous iterable and can be used forfor await... ofCycle.
// Create an asynchronous iterable
var asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0.next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }

        return Promise.resolve({ done: true}); }}; }};// Self-executing functions trigger asynchronous traversal
(async function() {
   for await (num of asyncIterable) {
     console.log(num);
   }
})();
Copy the code
  • Online sample

GlobalThis global object

  • globalThisProvides a standard way to get global views of different environmentsthisObject (that is, the global object itself). Don’t likewindoworselfThese properties ensure that they work in all environments with and without Windows. It can be used at easeglobalThis, don’t worry about its running environment. Just remember, for the sake of memorization, the global scopethisisglobalThis.

Optional chain operator? . es2020

  • Optional chain operator (? .) allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid.
  • ? .The function of the operator is similar to.The chain operator differs in that the reference is nullnullorundefinedWill not cause an error in the case of the expression short-circuit return value isundefined.
  • When used with a function call, returns if the given function does not existundefined.Throws an error if there is a field with the same name as the function
  • The optional chain operator cannot be used for assignment
let customer = {
  name: "Carl".details: {
    age: 82.location: "Paradise Falls" // Details' address attribute is undefined}};let customerCity = customer.details?.address?.city;

/ /... Optional chains can also be used with function calls
letduration = vacations.trip? .getTime? . ();Copy the code

Optional chains access array elements

let arr = [1]

letarrayItem = arr? .42];
console.log(arrayItem) // undefined

letarrayItem = arr? .0];
console.log(arrayItem) / / 1
Copy the code

Null-value merge operator?? es2020

  • Null-value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand.

  • With the logical or operator (| |), logical or operator will be on the left operand is false value returns the right operand.

const nullValue = null;
const emptyText = ""; // Empty string, false value, Boolean("") === false
const someNumber = 42;

const valA = nullValue ?? "Default values for valA";
const valB = emptyText ?? "Default value for valB";
const valC = someNumber ?? 0;

console.log(valA); // "Default value of valA"
console.log(valB); // "" (null string is false, but not null or undefined)
console.log(valC); / / 42
Copy the code

Cannot be shared with the AND OR OR operators OR an exception will be thrown.

/ / error
null || undefined ?? "foo"; / / throw SyntaxError
true || undefined ?? "foo"; / / throw SyntaxError

// Use parentheses correctly to explicitly indicate the priority of the operation
(null || undefined)??"foo"; / / return "foo"
Copy the code

Probably very few people can read it!