Writing in the front

Object and array deconstruction

Array deconstruction

const [a, b, c] = [1.2.3] // a 1 b 2 c3

const [a,,c] = [1.2.3] // a 1 c 3
Copy the code

Object deconstruction

const person = { name: 'huangyanting'.age: 3 }

const { name, age } = person
// name huangyanting age 3
Copy the code

The name variable here is nested in four layers, and if we still try to extract it the old way:

This does not work because the school object itself does not have a name property. Name is in the “son’s son” object of the school object. A clumsy way to extract the name is to deconstruct it layer by layer:

const school = {
    classes: {
        stu: {
            name: 'Bob'.age: 24,}}}Copy the code
const { classes } = school 
const { stu } = classes 
const { name } = stu name // 'Bob'
Copy the code

But there is a more standard way to solve this problem with a line of code:

const { classes: { stu: { name } }} = school 

name // 'Bob'
Copy the code

Object extension operation

Extension operators in objects (…) Retrieves all traversable properties from the parameter object and copies them to the current object. Here’s an example:

    const me = {
        name: 'tingGe'.age: 3
    }

    constmeCopy = { ... me } meCopy// {name: "tingGe", age: 3}
Copy the code

Here… “Me” is equivalent to writing:

Object.assign({}, me)
Copy the code

Array expansion operation

In arrays, an extension operation turns an array into a comma-separated sequence of arguments. Here’s an example:

console.log(... ['haha'.'hehe'.'xixi']) 
// haha hehe xixi
Copy the code
function mutiple(x, y) { 
     return x*y 
} 
const arr = [2.3] mutiple(... arr)/ / 6
Copy the code

Merging two arrays

const arr1 = [1.2.3.4] 
const arr2 = [5.6.7.8]
Copy the code

How to combine two arrays into one array. There are many possible ways to solve this problem, but one of the best looks is to use our extension:

const newArr = [...arr1, ...arr2]

Copy the code

Rest parameters are relatively familiar with some extender operations. But there is another side to the extension. When used with function parameters, it can also combine a separate sequence of arguments into an array:

function mutiple(... args) { let result = 1; for (var val of args) { result *= val; } return result; } mutiple(1, 2, 3, 4) // 24Copy the code
function mutiple(... args) { console.log(args) } mutiple(1, 2, 3, 4) // [1, 2, 3, 4]Copy the code

Class array conversion

Class array object, ecMA-262 defines it as:

1. It must be an object 2. It has the length property

By this standard, any object with the length attribute is an array-like object:

Const book = {name: 'How to read a book', age: 10, length: 300} // This is an array-like objectCopy the code

An array-like object is an object that has a length attribute and several index attributes

const book = { 
      0: 'how to read a book',
      1: 10, 
      length: 2 
}
Copy the code

In fact, array-like objects often have attributes with integer index names, but this is not required by definition. So both books above can be thought of as array-like objects.

Note the conversion of class arrays

How do I convert an array-like object into a real array?

const arrayLike = { 
         0: 'Bob',
         1: 'Lucy', 
         2: 'Daisy', 
         length: 3
}
Copy the code

The slice method on the Array prototype in ES5 – this method returns a copy of the Array if no arguments are passed, so it can be used to convert arrays of classes to arrays.

const arr = Array.prototype.slice.call(arrayLike);
Copy the code

Array.from method — This is a new Array method in ES6 that converts an Array of classes into an Array:

const arr = Array.from(arrayLike);
Copy the code

Extension operator — “…” It is also possible to convert an array-like object to an array if the traverser interface is deployed on the array-like object. In this case, arrayLike does not deploy the traverser interface, so this route does not work. But some objects, such as the arguments variable inside a function (which is also an array-like object), satisfy the criteria and can be converted this way:

Function demo() {console.log(' console.log ',[...arguments])} function demo(1, 2, 3, 4) {console.log(' console.log ',[...arguments])}Copy the code

Template syntax and string handling

let name = 'tingGE'
let career = 'coder'
let hobby = ['coding', 'writing']
let finalString = `
my name is ${name}, 
I work as a ${career} I love ${hobby[0]} 
and ${hobby[1]}`
console.log(finalString);

// my name is tingGE, I work as a coder,
// I love coding and writing
Copy the code

In template strings, whitespace, indentation, and newlines are reserved. Template strings fully support "operation" expressions, and you can do some calculations in ${}

A stronger approach

In addition to the template syntax, ES6 also added a series of string methods to improve our development efficiency. Extract the common parts of them, as follows:

Existence checks: In the past, indexOf > -1 was the only way to determine if a character/string was in a string. ES6 now provides three methods: includes, startsWith, and endsWith, all of which return a Boolean value to tell you if they exist.

  • Includes: Determines the relationship between strings and substrings.
const son = 'haha'
const father = 'xixi haha hehe'  
father.includes(son) // true
Copy the code
  • StartsWith: Determines whether a string begins with a/string character:
const father = 'xixi haha hehe' 
father.startsWith('haha') // false 
father.startsWith('xixi') // true
Copy the code

Automatic repetition: We can use the repeat method to print the same string multiple times (to be copied consecutively)

const sourceCode = 'repeat for 3 times; ' const repeated = sourceCode.repeat(3) console.log(repeated) // repeat for 3 times; repeat for 3 times; repeat for 3 times;Copy the code

Merge air transport operator??

Assume that variable does not exist, hope to have a default value, usually use | | operators. But in the hollow javascript string 0, false will perform | | operators, ECMAScript2020 combined air operator is applied to deal with the problem, only allowed when the value is null or undefined using default values.

const name = '';
console.log(name || 'zz'); // zz;
console.log(name ?? 'zz'); // '';
Copy the code

Optional chain operators? .

It’s common in business code to have an object a with an attribute B, and an object B with an attribute C.

const a = {  
   b: {   
      c: 123,   
      }
}
Copy the code

Accessing c is often written as A.B.C, but an error occurs if B does not exist.

ECMAScript2020 defines optional chain operators to solve this problem in. Before I add one? Make the key name optional.

let person = {}; console.log(person? .profile? .age ?? 18); / / 18Copy the code

Dynamic import import

Import (‘./a.js’) returns a Promise object.

const a = 123;
export { a };
Copy the code
import('./a.js').then(data => { console.log(data.a); / / 123; });Copy the code

String.prototype.replaceAll()

For the convenience of the global String replacement, ES2021 will support String. The prototype. The replaceAll () method, which don’t have to write a regular expression can be completed the global replacement of the String.

'abc555'.replaceAll('5', '2'); // abc222
Copy the code

Promise.allSettled

When dealing with multiple promises, especially if they depend on each other, it is necessary to log what happens to each Promise to debug errors.

With Promise.allSettled, you can create a new Promise that returns an array containing the data for each Promise only when all the promises passed to it are complete.

const p1 = new Promise((res, rej) => setTimeout(res, 1000));
const p2 = new Promise((res, rej) => setTimeout(rej, 1000));
Promise.allSettled([p1, p2]).then(data => console.log(data));

[ Object { status: "fulfilled", value: undefined},
  Object { status: "rejected", reason: undefined} ]
Copy the code

Promise.all ends when multiple promises succeed or when the first one fails. Promise.allSettled is when everything executes successfully or unsuccessfully.

Promise.any

As long as there is a promise is a pity, then return a resolved promise; If all the promises are Rejected, return a Rejected Promise

Promise.any([ Promise.reject(1), Promise.resolve(2) ])
.then(result => console.log('result:', result)) 
.catch(error => console.error('error:', error)); // result: 2
Copy the code

For of supports asynchronous iteration

Before we do that we want to implement asynchronous iteration and we want to nest an async function in the for of layer

async function () { for (const fn of actions) { await fn(); }}Copy the code

ES2018 offers a new way of writing.

async function() { for await (const fn of actions) { fn(); }}Copy the code