Study seven, ES2016 new feature summary, ES2017 new feature summary

1. ECMAScript2016 version overview

1、Array.includes();

You can find whether there is a parameter in the array, including NaN.

The previous indexOf can return the subscript of a parameter in the array, but it cannot confirm whether it contains NaN.

const arr = ['foo', 1, NaN, false]
// 找到返回元素下标
console.log(arr.indexOf('foo'))
// 找不到返回 -1
console.log(arr.indexOf('bar'))
// 无法找到数组中的 NaN
console.log(arr.indexOf(NaN))
// 直接返回是否存在指定元素
console.log(arr.includes('foo'))
// 能够查找 NaN
console.log(arr.includes(NaN))

2. Exponent operator: **

Math.pow(2,10) is equivalent to 2 ** 10

console.log(Math.pow(2, 10))
console.log(2 ** 10)

Two, ECMAScript2017 version overview

1. Object.values(obj) returns an array of all values ​​of obj, and the former Object.keys(obj) returns an array of all keys.

const obj = {
  foo: 'value1',
  bar: 'value2'
}
console.log(Object.values(obj))

2. Object.entries(obj) can return an object that can use for...of, and then we can safely convert this object into a Map object new Map();

console.log(Object.entries(obj))
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value)
}
console.log(new Map(Object.entries(obj)))

3. Object.getOwnPropertyDescriptors, since ES2015 we can add get/set methods to objects,

    We cannot use the assgin method to completely copy the set/get method of an object, but after getOwnPropertyDescriptors is wrapped,

    You can use defineProperties instead of assgin to completely copy an object.  

const p1 = {
  firstName: 'Lei',
  lastName: 'Wang',
  get fullName () {
    return this.firstName + ' ' + this.lastName
  }
}
console.log(p1.fullName)

const p2 = Object.assign({}, p1)
p2.firstName = 'zce'
console.log(p2)

const descriptors = Object.getOwnPropertyDescriptors(p1)
// console.log(descriptors)
const p3 = Object.defineProperties({}, descriptors)
p3.firstName = 'zce'
console.log(p3.fullName)

4. padStart and padEnd are filled with the given string until our target string reaches the length we specify.

const books = {
  html: 5,
  css: 16,
  javascript: 128
}
for (const [name, count] of Object.entries(books)) {
  console.log(name, count)
}
for (const [name, count] of Object.entries(books)) {
  console.log(`${name.padEnd(16, '-')}|${count.toString().padStart(3, '0')}`)
}

5. Trailing commas are allowed in function parameters.

function foo (
  bar,
  baz,
) {}

6. Async/await: Syntactic sugar for Promise.

async function main () {
    const users = await ajax('/api/users.json')
}

 

Guess you like

Origin blog.csdn.net/qq_40289624/article/details/108838765