preface

Hello everyone, first of all, the title is not malicious haha. Please excuse the chicken. Are to help everyone, everyone can know a few of their own, how many points, posted in the message ha. Each score is one for a total of 38 points

Hello everyone, I am Lin Sanxin. Many brothers and sisters come to ask me questions these days, and I have seen a lot of their codes. It seems to me that the use of code is still in the ES5 phase, and I don’t know much about the new syntax that would be easy to implement, so I decided to write an article summarizing the very useful ES6, ES7, ES8, ES9, ES10, ES11, and ES12 syntax that I have used in my work.

First of all: I just cite the most basic example here, but how to use the project flexibly, this is for each student to explore.

ES6

1, let and const

The appearance of these two is always felt to be for the development of code specifications. We should gradually abandon var and use more lets and const in our projects

The difference with var:

  • Var has variable promotion, initialization promotion, variable value
  • Let has variable promotion, no initial promotion, variable value
  • Const has variable promotion, no initial promotion, and is immutable in value, but mutable in property if the object is defined

Let and const have variable increments, but not initialized increments:

var name = 'Lin SAN Xin'

function fn () {
  console.log(name)
  let name = 'sunshin_lin'
}
fn() // Cannot access 'name' before initialization
Copy the code

Block-level scoping solves the problem:

for(var i = 0; i < 5; i++) {
  setTimeout(() = > {
    console.log(i)
  })
} // 5 5 5 5 5 5


for(let i = 0; i < 5; i++) {
  setTimeout(() = > {
    console.log(i)
  })
} // 0 1 2 3 4
Copy the code

2. Default parameters

In development you’ve had the problem of setting default parameters if they don’t come in

function fn (name, age) {
  var name = name || 'Lin SAN Xin'
  var age = age || 18
  console.log(name, age)
}
fn() // Lin Sanxin 18
Copy the code

But that’s not very elegant. You can use ES6’s default arguments

function fn (name = 'Lin SAN Xin', age = 18) {
  console.log(name, age)
}
fn() // Lin Sanxin 18
fn('sunshine'.22) // sunshine 22
Copy the code

3. Extension operators

There was a time when I wanted to concatenate multiple arrays, and that was all I could do

const arr1 = [1.2.4]
const arr2 = [4.5.7]
const arr3 = [7.8.9]

const arr = arr1.concat(arr2).concat(arr3)
[
  1.2.4.4.5.7.7.8.9
]
Copy the code

Now I can do it more elegantly

const arr1 = [1.2.4]
const arr2 = [4.5.7]
const arr3 = [7.8.9]

const arr = [...arr1, ...arr2, ...arr3]
[
  1.2.4.4.5.7.7.8.9
]
Copy the code

4. Remaining parameters

You’ve probably seen this problem, a function, you don’t know how many arguments you’re passing in, so you can use the rest of ES6’s arguments

function fn (name, ... params) {
  console.log(name)
  console.log(params)
}
fn ('Lin SAN Xin'.1.2) // Lin Sanxin [1, 2]
fn ('Lin SAN Xin'.1.2.3.4.5) // Lin Sanxin [1, 2, 3, 4, 5]
Copy the code

5. Template string

In my old days, this was the only way I could concatenate strings

const name = 'Lin SAN Xin'
const age = '22'

console.log(name + 'this year' + age + 'years old!) // Lin Sanxin is 22 years old
Copy the code

Now I can do this. It’s more elegant

const name = 'Lin SAN Xin'
const age = '22'

console.log(`${name}This year,${age}` age?) // Lin Sanxin is 22 years old
Copy the code

6, the Object. The keys

Can be used to get the collection of keys of an object, and in turn, to get the value of the corresponding key

const obj = {
  name: 'Lin SAN Xin'.age: 22.gender: 'male'
}

const keys = Object.keys(obj)
console.log(keys) // [ 'name', 'age', 'gender' ]
Copy the code

7. Arrow function

Before, we used normal functions

function fn () {}

const fn = function () {}
Copy the code

ES6 has added arrow functions

const fn = () = > {}

// If there is only one argument, the parentheses can be omitted
const fn = name= > {}

// If there is only one return in the function body
const fn = name= > {
    return 2 * name
}
// can be abbreviated as
const fn = name= > 2 * name
// If an object is returned
const fn = name= > ({ name: name })
Copy the code

The difference between normal function and arrow function:

  • The arrow function cannot be used as a constructor. You cannot use new
  • 2. The arrow function does not have its own this
  • The arrow function has no arguments object
  • Arrow functions have no prototype objects

8, Array. ForEach

ES6 adds new array traversal method

const eachArr = [1.2.3.4.5]

// Three arguments: traversing the item index array itself
// Match the arrow function
eachArr.forEach((item, index, arr) = > {
  console.log(item, index, arr)
})
1 0 [ 1.2.3.4.5 ]
2 1 [ 1.2.3.4.5 ]
3 2 [ 1.2.3.4.5 ]
4 3 [ 1.2.3.4.5 ]
5 4 [ 1.2.3.4.5 ]
Copy the code

9, Array. The map

Often used to return a new array after processing

const mapArr = [1.2.3.4.5]

// Three arguments: traversing the item index array itself
// Double each element with the arrow function
const mapArr2 = mapArr.map((num, index, arr) = > 2 * num)
console.log(mapArr2)
[ 2.4.6.8.10 ]
Copy the code

10., Array filter

As the name suggests, a method for filtering

const filterArr = [1.2.3.4.5]

// Three arguments: traversing the item index array itself
// In conjunction with the arrow function, returns a set greater than 3
const filterArr2 = filterArr.filter((num, index, arr) = > num > 3)
console.log(filterArr2)
[ 4.5 ]
Copy the code

11, Array. Some

‘some’ means only one of them is true, so it returns true

const someArr = [false.true.false.true.false]

// Three arguments: traversing the item index array itself
// With the arrow function, return true if one is true, and false if neither is true
const someArr2 = someArr.some((bol, index, arr) = > bol)
console.log(someArr2)
true
Copy the code

12, Array. Every

Every is the opposite of some. Some is just one. Every returns true if all of them are true

const everyArr = [false.true.false.true.false]

// Three arguments: traversing the item index array itself
// With the arrow function, return true if everything is true, otherwise return false
const everyArr2 = everyArr.every((bol, index, arr) = > bol)
console.log(everyArr2)
Copy the code

13, Array. Reduce

  • The first argument callback: pre is the value of the last return, and next is the item of the array traversed this time
  • The second parameter is the initial value and the first pre

Here are two examples:

// Calculate 1 + 2 + 3 + 4 + 5
const reduceArr = [1.2.3.4.5]
const sum = reduceArr.reduce((pre, next) = > {
  return pre + next
}, 0)
console.log(sum) / / 15

// Count the number of elements
const nameArr = ['Lin SAN Xin'.'sunshine_lin'.'Lin SAN Xin'.'Lin SAN Xin'.'kobe Bryant]
const totalObj = nameArr.reduce((pre, next) = > {
  if (pre[next]) {
    pre[next]++
  } else {
    pre[next] = 1
  }
  return pre
}, {})
console.log(totalObj) // {' sunshine_lin ': 3, 'sunshine_lin ': 1}

Copy the code

14. Shorthand for object properties with the same name

That’s what we used to write for properties with the same name

const name = 'Lin SAN Xin'
const age = '22'

const obj = {
  name: name,
  age: age
}

console.log(obj) // {name: 'Lin Sanxin ', age: '22'}
Copy the code

ES6 added syntax, just write this

const name = 'Lin SAN Xin'
const age = '22'

// Attributes with the same name can be abbreviated
const obj = {
  name
  age
}

console.log(obj) // {name: 'Lin Sanxin ', age: '22'}
Copy the code

15, Promise

Where is the Promise? The promise was that once his state changed, it wouldn’t change. Here are the basics, if you want to get a deeper understanding of how to use them, check out another of my articles, writing Promise principles, the most accessible version!!

Look at basic usage

  • The successful state
function requestData () {
  // Simulate the request
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve('Lin SAN Xin')},1000)
  })
}

requestData().then(res= > {
  console.log(res) // Output 'Lin Sanxin' after 1 second
}, err= > {
  console.log(err)
})
Copy the code
  • The failure state
function requestData () {
  // Simulate the request
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      reject('Wrong.')},1000)
  })
}

requestData().then(res= > {
  console.log(res)
}, err= > {
  console.log(err) // Output 'error' after one second
})
Copy the code
  • allmethods
    • Receive an array of promises. If there are non-Promise items in the array, the item is considered successful
    • If all promises are successful, an array of successful results is returned
    • If a Promise fails, the failed result is returned
// If all is successful
function fn(time) {
  return new Promise((resolve, reject) = > {
    console.log(88)
    setTimeout(() = > {
      resolve(`${time}Milliseconds later I succeeded!! `)
    }, time)
  })
}

Promise.all([fn(2000), fn(3000), fn(1000)]).then(res= > {
  // Output after 3 seconds [' I succeeded after 2000 milliseconds!! ', 'I succeeded after 3000 milliseconds!! ',' I succeeded after 1000 milliseconds!! ']
  console.log(res) 
}, err= > {
  console.log(err)
})



// If one fails
function fn(time, isResolve) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      isResolve ? resolve(`${time}Milliseconds later I succeeded!! `) : reject(`${time}Milliseconds later I failed!! `)
    }, time)
  })
}

Promise.all([fn(2000.true), fn(3000), fn(1000.true)]).then(res= > {
  console.log(res)
}, err= > {
  console.log(err) // after 3 seconds output 'I failed after 3000 milliseconds!! '
})
Copy the code
  • racemethods
    • Receive an array of promises. If there are non-Promise items in the array, the item is considered successful
    • Whichever Promise gets the result fastest returns that result, whether it succeeds or fails
function fn(time, isResolve) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      isResolve ? resolve(`${time}Milliseconds later I succeeded!! `) : reject(`${time}Milliseconds later I failed!! `)
    }, time)
  })
}

Promise.race([fn(2000.true), fn(3000), fn(1000)]).then(res= > {
  console.log(res)
}, err= > {
  console.log(err) // Output after 1 second
})
Copy the code

16, class

We used to use constructors to generate objects, so let’s do this

function Person(name) {
  this.name = name
}

Person.prototype.sayName = function () {
  console.log(this.name)
}

const kobe = new Person('kobe Bryant)
kobe.sayName() / / kobe Bryant
Copy the code

With THE ES6 class, you can do that

class Person {
  constructor(name) {
    / / the constructor
    this.name = name
  }

  sayName() {
    console.log(this.name)
  }
}

const kobe = new Person('kobe Bryant)
kobe.sayName() / / kobe Bryant
Copy the code

It is worth mentioning that class is also function, class is the syntactic sugar of function

class Person {}

console.log(typeof Person) // function
Copy the code

In addition to the above, you need to know the following about class

Static properties and methods: Static properties and methods defined using static can only be used by the class itself

class Person {
  constructor(name) {
    this.name = name
  }

  static age = 22

  static fn() {
    console.log('ha ha')}}console.log(Person.age) / / 22
Person.fn() / / ha ha

const sunshine_lin = new Person('Lin SAN Xin')
console.log(sunshine_lin.age) // undefined
sunshine_lin.fn() // fn is not a function
Copy the code

The extend inheritance

class Animal {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
}

class Cat extends Animal {
  say() {
    console.log(this.name, this.age)
  }
}

const cat = new Cat('ketty'.5) // Inherit the Animal constructor
cat.say() // ketty 5

Copy the code

17. Deconstruct the assignment

You used to do this if you wanted to extract properties from an object

const obj = {
  name: 'Lin SAN Xin'.age: 22.gender: 'male'
}

const name = obj.name
const age = obj.age
const gender = obj.gender
console.log(name, age, gender) // Lin Sanxin is 22 male
Copy the code

New syntax for deconstructing assignments in ES6

const obj = {
  name: 'Lin SAN Xin'.age: 22.gender: 'male'.doing: {
    morning: 'fishing'.afternoon: 'fishing'.evening: 'sleep'}}const { name, age, gender } = obj
console.log(name, age, gender) // Lin Sanxin is 22 male

// Deconstruct duplicate names
const { name: myname } = obj
console.log(myname) / / Lin three hearts

// Nested deconstruction
const { doing: { evening } } = obj
console.log(evening) // sleep
Copy the code

You can also deconstruct arrays

const arr = [1.2.3]

const [a, b, c] = arr
console.log(a, b, c) / / 1 2 3

// Default assignment
const [a, b, c, d = 5] = arr
console.log(a, b, c, d) // 1, 2, 3, 5

// Deconstruct out of order
const { 1: a, 0: b, 2: c } = arr
console.log(a, b, c) / / 1 2 3
Copy the code

Find and findIndex

  • If the element is not found, undefined is returned
  • FindIndex: if found, returns the index of the element found. If not, returns -1
Const findArr = [{name: 'kobe, no:' 24 '}, {name: "rose", no: '1'}, {name: 'the radmanovic, no: '0'}] const kobe = findarr. find(({name}) => name === 'kobe ') const kobeIndex = findarr. findIndex(({name}) => name = = = 'kobe Bryant) console. The log (kobe) / / {name:' kobe, no: '24'} the console. The log (kobeIndex) / / 0Copy the code

19, for and for

  • For in: Traversal method that traverses objects and arrays
  • For of: traversal method, which can only traverse groups, not objects

For in:

const obj = { name: 'Lin SAN Xin'.age: 22.gender: 'male' }
const arr = [1.2.3.4.5]

for(let key in obj) {
  console.log(key)
}
name
age
gender

for(let index in arr) {
  console.log(index)
}
0 1 2 3 4
Copy the code

For of:

for(let item of arr) {
  console.log(item)
}
1 2 3 4 5
Copy the code

20. Set and Map

  • Set

Let’s start with the basic use of Set

// Do not pass the array
const set1 = new Set()
set1.add(1)
set1.add(2)
console.log(set1) // Set(2) { 1, 2 }

// You can also pass an array
const set2 = new Set([1.2.3])
// Add elements using add
set2.add(4)
set2.add('Lin SAN Xin')
console.log(set2) // Set(5) {1, 2, 3, 4, '1'}
// Whether to use has for an element
console.log(set2.has(2)) // true
// Use size to view the length
console.log(set2.size) / / 5
// Delete elements using delete
set2.delete(2)
console.log(set2) // Set(4) {1, 3, 4, '1'}
Copy the code

Now let’s talk about the unrepeatability of sets

// If an existing element is added, the increment is invalid and will be automatically deduplicated
const set1 = new Set([1])
set1.add(1)
console.log(set1) // Set(1) { 1 }

// The array is passed with duplicates, which are automatically removed
const set2 = new Set([1.2.'Lin SAN Xin'.3.3.'Lin SAN Xin'])
console.log(set2) // Set(4) {1, 2, 3}
Copy the code

Note the reference data type and NaN in the Set non-repeatability

// Both objects are not used Pointers, so they cannot be reused
const set1 = new Set([1, {name: 'Lin SAN Xin'}, 2, {name: 'Lin SAN Xin'}])
console.log(set1) / / Set (4) {1, {name: 'three heart Lin'}, 2, {name: 'three heart Lin'}}


// If two objects are the same pointer, you can deduplicate them
const obj = {name: 'Lin SAN Xin'}
const set2 = new Set([1, obj, 2, obj])
console.log(set2) // Set(3) {1, {name: 'linsanxin'}, 2}We all know thatNaN! = =NaN.NaNIt's not equal to itself, but it's inSetHe's still gonna get hitconst set = new Set([1.NaN.1.NaN])
console.log(set) // Set(2) { 1, NaN }
Copy the code

Arrays can be de-duplicated by taking advantage of the unrepeatability of sets

const arr = [1.2.3.4.4.5.5.66.9.1]

// Set can be converted to an array using the extension operator
const quchongArr = [...new Set(arr)]
console.log(quchongArr) // [1, 2, 3, 4, 5, 66, 9]
Copy the code
  • Map

The biggest advantage of Map versus object is that key is not restricted by type

/ / define the map
const map1 = new Map(a)Set (key, value)
map1.set(true.1)
map1.set(1.2)
map1.set('ha ha'.'Hee hee hee')
console.log(map1) // Map(3) {true => 1, 1 => 2, 'ha' => 'hee hee'}
// Determine whether a map has a key.
console.log(map1.has('ha ha')) // true
// Use get(key) to obtain the value corresponding to a key in the map.
console.log(map1.get(true)) / / 2
// Delete a key-value pair from a map using delete(key)
map1.delete('ha ha')
console.log(map1) // Map(2) { true => 1, 1 => 2 }

// Define a map. You can also pass in an array of key-value pairs
const map2 = new Map([[true.1], [1.2], ['ha ha'.'Hee hee hee']])
console.log(map2) // Map(3) {true => 1, 1 => 2, 'ha' => 'hee hee'}
Copy the code

ES7

21, includes

Return true if it can be found in the array, false otherwise

const includeArr = [1.2 , 3.'Lin SAN Xin'.'kobe Bryant]

const isKobe = includeArr.includes('kobe Bryant)
console.log(isKobe) // true
Copy the code

It’s very similar to indexOf, but there are differences

const arr = [1.2.NaN]

console.log(arr.indexOf(NaN)) // -1 indexOf could not find NaN
console.log(arr.includes(NaN)) // True includes can find NaN
Copy the code

22. Exponentiation operator

Before exponentiation, we had to write it this way

const num = Math.pow(3.2) / / 9
Copy the code

ES7 provides the exponentiation operator: **

const num = 3ζ”―ι‚£2 / / 9
Copy the code

ES8

23, Object values

A collection of values that can be used to get an object

const obj = {
  name: 'Lin SAN Xin'.age: 22.gender: 'male'
}

const values = Object.values(obj)
console.log(values) // [' Lin Sanxin ', 22, 'male']
Copy the code

24 and the Object. Entries

Can be used to get a collection of key-value pairs for an object

const obj = {
  name: 'Lin SAN Xin'.age: 22.gender: 'male'
}

const entries = Object.entries(obj)
console.log(entries) 
/ / [[' name ', 'Lin three heart], [' age, 22], [' gender' and 'male']]
Copy the code

25, async/await

Perform an asynchronous operation in a synchronous manner

We might encounter a scenario where interface 1 requests data 1, and data 1 is used as a parameter to request data 2. We would use a Promise to do this

function fn() {
  // Simulate the first request
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(5)},1000)
  }).then(res= > {
    // Simulate the second request
    new Promise((resolve, reject) = > {
      setTimeout(() = > {
        // Take the data from the first request and multiply it by 10 as the data from the second request
        resolve(res * 10)},2000)
    }).then(sres= > {
      console.log(sres)
    })

  })
}
fn() // 1 + 2 = 3 output 50 after 3 seconds
Copy the code

If there are many interfaces, there will be many layers nested. In this case, we can use async/await to perform asynchrony in a synchronous manner. Note the following:

  • Await can only be used in async functions
  • It is better to follow “await” with “Promise”, if followed by an ordinary function, it will execute directly
  • The async function returns a Promise
function fn1 () {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(5)},1000)})}function fn2 (data) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(data * 10)},2000)})}async function req () {
  // Perform asynchrony in synchronous mode, like queuing
  const data1 = await fn1() // Wait one second to return the data
  const data2 = await fn2(data1) // Take data1 to request 2 seconds later, go down
  console.log(data2) // Output 50 after 3 seconds
}
req()
Copy the code

ES9

26, for await of the await

Let’s look at the following scenario

function fn (time) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(`${time}Milliseconds later I succeeded!! `)
    }, time)
  })
}

fn(3000).then(res= > console.log(res))
fn(1000).then(res= > console.log(res))
fn(2000).then(res= > console.log (res)) as a result1000Milliseconds later I succeeded!!2000Milliseconds later I succeeded!!3000Milliseconds later I succeeded!!Copy the code

But I want this result

3000Milliseconds later I succeeded!!1000Milliseconds later I succeeded!!2000Milliseconds later I succeeded!!Copy the code

The first thing we definitely think of is async/await

function fn (time) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(`${time}Milliseconds later I succeeded!! `)
    }, time)
  })
}

async function asyncFn () {
  / / in line
  const data1 = await fn(3000)
  console.log(data1) // 3 seconds later, 3000 milliseconds later, I succeeded!!
  const data2 = await fn(1000)
  console.log(data2) // After 1 second, 1000 milliseconds, I succeeded!!
  const data3 = await fn(2000)
  console.log(data3) // After 2 seconds, 2000 milliseconds, I succeeded!!
}
Copy the code

However, the above code also has disadvantages. If there are dozens of await, it does not mean writing dozens of await. Is there a way to output them through a loop?

function fn (time) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      resolve(`${time}Milliseconds later I succeeded!! `)
    }, time)
  })
}

async function asyncFn () {
  const arr = [fn(3000), fn(1000), fn(1000), fn(2000), fn(500)]
  for await (let x of arr) {
    console.log(x)
  }
}

asyncFn()
3000Milliseconds later I succeeded!!1000Milliseconds later I succeeded!!1000Milliseconds later I succeeded!!2000Milliseconds later I succeeded!!500Milliseconds later I succeeded!!Copy the code

27, Promise. Finally

The new Promise method executes this function regardless of the failure or success status

// cheng
new Promise((resolve, reject) = > {
  resolve('There you go')
}).then(
  res= > { console.log(res) },
  err= > { console.log(err) }
).finally(() = > { console.log('I am finally')})new Promise((resolve, reject) = > {
  reject('Failed.')
}).then(
  res= > { console.log(res) },
  err= > { console.log(err) }
).finally(() = > { console.log('I am finally')})Copy the code

ES10

28, Array. Flat

I have a two-dimensional array, and I want it to be a one-dimensional array:

const arr = [1.2.3[4.5.6]]

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

You can also pass a parameter, which is the number of times to reduce the dimension

const arr = [1.2.3[4.5.6[7.8.9]]]

console.log(arr.flat(2))1.2.3.4.5.6.7.8.9
]
Copy the code

If you pass an infinite number, you have reduced the multidimensional array (no matter how many dimensions) to a one-dimensional array

const arr = [1.2.3[4.5.6[7.8.9[10.11.12]]]]

console.log(arr.flat(Infinity))1.2.3.4.5.6.7.8.9.10.11.12
]
Copy the code

29, Array. FlatMap

Here’s a need for you

let arr = ["Kobe, James, Anthony"."Lillard Ross McCollum"];
Copy the code

Convert the above array to

[ 'kobe Bryant.'James'.'Anthony'.'Lillard'.'rose'.'McCollum' ]
Copy the code

The first thing I thought of was map + flat

console.log(arr.map(x= > x.split("")).flat());
// [' Kobe ', 'lebron ',' Anthony ', 'Lillard ',' Rose ', 'McCollum']
Copy the code

A flatMap is a flat + map, where one method has two

console.log(arr.flatMap(x= > x.split("")));
// [' Kobe ', 'lebron ',' Anthony ', 'Lillard ',' Rose ', 'McCollum']
Copy the code

30, BigInt,

BigInt is a new JavaScript data type added to ES10 to represent integers greater than 2^ 53-1, which is the largest number that JavaScript can represent before ES10

const theBiggestInt = 9007199254740991n;

const alsoHuge = BigInt(9007199254740991);
// 9007199254740991n

const hugeString = BigInt("9007199254740991");
// 9007199254740991n

const hugeHex = BigInt("0x1fffffffffffff");
// 9007199254740991n

const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
// 9007199254740991n
Copy the code

By the way, since this is a new data type in JavaScript, what is its typeof?

const bigNum = BigInt(1728371927189372189739217)
console.log(typeof bigNum) // bigint
Copy the code

So when an interviewer asks you how many data types there are in JavaScript, instead of 6, say 8. Add ES6 Symbol and ES10 BigInt

31, Object. FromEntries

Entries in the previous ES8 Object. Entries turned objects into an array of key-value pairs, while object. fromEntries did the opposite, turning an array of key-value pairs into objects

const arr = [
  ['name'.'Lin SAN Xin'],
  ['age'.22],
  ['gender'.'male']]console.log(Object.fromEntries(arr)) // {name: 'Lin SAN xin ', age: 22, gender:' male '}
Copy the code

It is also useful for turning maps into objects

const map = new Map()
map.set('name'.'Lin SAN Xin')
map.set('age'.22)
map.set('gender'.'male')

console.log(map) / / the Map (3) {' name '= >' Lin three heart ', 'age' = > 22, 'gender' = > 'male'}

const obj = Object.fromEntries(map)
console.log(obj) // {name: 'Lin SAN xin ', age: 22, gender:' male '}
Copy the code

32, String. TrimStart && String. TrimEnd

We all know that JavaScript has a trim method that clears whitespace at the beginning and end of a string

const str = '    ζž—δΈ‰εΏƒ    '
console.log(str.trim()) // 'Lin Sanxin'
Copy the code

TrimStart and trimEnd are used to separate whitespace from the beginning and end of a string

const str = '    ζž—δΈ‰εΏƒ    '

// Remove the header space
console.log(str.trimStart()) // 'Lin Sanxin'
// Remove trailing whitespace
console.log(str.trimStart()) // 'Lin Sanxin'
Copy the code

ES11

33, Promise. AllSettled

ES11 new Promise method

  • Receive an array of promises. If there are non-Promise items in the array, the item is considered successful
  • Collect the result of each Promise into an array and return it
function fn(time, isResolve) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      isResolve ? resolve(`${time}Milliseconds later I succeeded!! `) : reject(`${time}Milliseconds later I failed!! `)
    }, time)
  })
}

Promise.allSettled([fn(2000.true), fn(3000), fn(1000)]).then(res= > {
  console.log(res)
  // Output after 3 seconds[{status: 'fulfilled'.value: '2000 milliseconds later I did it!! ' },
  { status: 'rejected'.reason: 'After 3000 milliseconds I failed!! ' },
  { status: 'rejected'.reason: 'After 1000 milliseconds I failed!! '}]})Copy the code

34、?. ε’Œ ??

  • First,? ., Chinese nameOptional chain

Let’s say we need a variable that’s an array and has a length in order to do something

const list = null
// do something
if (list && list.length) {
  // do something
}

// Use an optional chain
const list = null
// do something
if(list? .length) {// do something
}
Copy the code

Let’s say I have an object, and I’m going to take a value that probably doesn’t exist, and we’re not even sure that obj exists

const obj = {
  cat: {
    name: 'ha ha'}}const dog = obj && obj.dog && obj.dog.name // undefined

/ / optional link chain
const obj = {
  cat: {
    name: 'ha ha'}}constdog = obj? .dog? .name// undefined
Copy the code

Let’s say I have an array, I’m not sure if it exists, but if it does, I take an index of one

const arr = null
// do something
const item = arr && arr[1]

/ / optional link chain
const arr = null
// do something
constitem = arr? .1]
Copy the code

Let’s say we have a function, we’re not sure if it exists, and if it does, we execute it

const fn = null
// do something
const res = fn && fn()

/ / optional link chain
const fn = null
// do something
constres = fn? . ()Copy the code
  • Say again??, Chinese nameVacancy merge operator

Please see the following code, we use | | operators, as long as the left is false, will return to the right of the data

const a = 0 || 'Lin SAN Xin' / / Lin three hearts
const b = ' ' || 'Lin SAN Xin' / / Lin three hearts
const c = false || 'Lin SAN Xin' / / Lin three hearts
const d = undefined || 'Lin SAN Xin' / / Lin three hearts
const e = null || 'Lin SAN Xin' / / Lin three hearts
Copy the code

And???? And | | the biggest difference is that in?? Here, only undefined and NULL are false

const a = 0 ?? 'Lin SAN Xin' / / 0
const b = ' ' ?? 'Lin SAN Xin' / /"
const c = false ?? 'Lin SAN Xin' // false
const d = undefined ?? 'Lin SAN Xin' / / Lin three hearts
const e = null ?? 'Lin SAN Xin' / / Lin three hearts
Copy the code

ES12

35, Promise. Any

E12 new Promise method

  • Receive an array of promises. If there are non-Promise items in the array, the item is considered successful
  • If a Promise succeeds, the success result is returned
  • If all promises fail, an error is reported
// When there is a success, return the fastest success
function fn(time, isResolve) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      isResolve ? resolve(`${time}Milliseconds later I succeeded!! `) : reject(`${time}Milliseconds later I failed!! `)
    }, time)
  })
}

Promise.any([fn(2000.true), fn(3000), fn(1000.true)]).then(res= > {
  console.log(res) // After 1 second output 1000 milliseconds I succeeded
}, err= > {
  console.log(err)
})

// When all else fails
function fn(time, isResolve) {
  return new Promise((resolve, reject) = > {
    setTimeout(() = > {
      isResolve ? resolve(`${time}Milliseconds later I succeeded!! `) : reject(`${time}Milliseconds later I failed!! `)
    }, time)
  })
}

Promise.any([fn(2000), fn(3000), fn(1000)]).then(res= > {
  console.log(res)
}, err= > {
  console.log(err) // All Error is reported after 3 seconds
})
Copy the code

36. Number separator

The number separator allows you to define long numbers more easily

const num = 1000000000

// Use number separators
const num = 1 _000_000_000
Copy the code

37, | | = and && =

Or equal to the (| | =) a | | = b is equivalent to a | | (a = b); A &&= b is the same as a && (a = b);Copy the code

I don’t know what ES is

38. Dynamic properties of objects

We often encounter such a problem. No matter in wechat applet or React, we need to modify a certain data according to a certain condition

if (type === 'boy') {
  this.setData({
    boyName: name
  })
} else if (type === 'girl') {
  this.setData({
    girlName: name
  })
}
Copy the code

I don’t know what this new feature is called, so I’ll just call it properties Dynamic properties hahaha

this.setData({
  [`${type}Name`]: name
})
Copy the code

conclusion

Many methods I only talk about the most basic, specific in the development of how to flexibly use, students can explore their own ha, this is difficult to teach, can only rely on theory + practice + accumulation

If you think this article has helped you in any way, please give it a thumbs-up.

Study group please click here, study together, fish together!!