一些常用的ES知识点

207 阅读2分钟

ES7

求幂运算符

以前求幂,我们需要这么写

const num = Math.pow(3, 2) // 9 复制代码

ES7提供了求幂运算符:**

const num = 3 ** 2 // 9

ES8

Object.values

可以用来获取对象的value的集合

const obj = {   name: '林三心',   age: 22,   gender: '男' } 
const values = Object.values(obj) console.log(values) 
// [ '林三心', 22, '男' ]

Object.entries

可以用来获取对象的键值对集合

const obj = {   name: '林三心',   age: 22,   gender: '男' } 
const entries = Object.entries(obj) console.log(entries)  
// [ [ 'name', '林三心' ], [ 'age', 22 ], [ 'gender', '男' ] ]

ES9

26、for await of

function fn (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time}毫秒后我成功啦!!!`)
    }, time)
  })
}

async function asyncFn () {
  // 排队
  const data1 = await fn(3000)
  console.log(data1) // 3秒后 3000毫秒后我成功啦!!!
  const data2 = await fn(1000)
  console.log(data2) // 再过1秒 1000毫秒后我成功啦!!!
  const data3 = await fn(2000)
  console.log(data3) // 再过2秒 2000毫秒后我成功啦!!!
}

但是上面代码也是有缺点的,如果有几十个,那不是得写几十个await,有没有一种方法可以通过循环来输出呢?

function fn (time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time}毫秒后我成功啦!!!`)
    }, 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()
3000毫秒后我成功啦!!!
1000毫秒后我成功啦!!!
1000毫秒后我成功啦!!!
2000毫秒后我成功啦!!!
500毫秒后我成功啦!!!

Promise.finally

新增的Promise方法,无论失败或者成功状态,都会执行这个函数

// cheng
new Promise((resolve, reject) => {
  resolve('成功喽')
}).then(
  res => { console.log(res) },
  err => { console.log(err) }
).finally(() => { console.log('我是finally') })

ES10

// Array.flat
// 如果传的是一个无限大的数字,那么就实现了多维数组(无论几维)降为一维数组
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]

ES11

?.

可选链

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

// 使用可选链
const list = null
// do something
if (list?.length) {
  // do something
}

后面跟变量或者函数时候的写法

// 跟特殊字符
a?.['aa/ghgg']
// 跟函数,等价于有a执行,()内代表传参
a?.({a:1})

??

??和||最大的区别是,在??这,只有undefined和null才算假值

const a = 0 ?? '林三心' // 0
const b = '' ?? '林三心' // ''
const c = false ?? '林三心' // false
const d = undefined ?? '林三心' // 林三心
const e = null ?? '林三心' // 林三心

const a = 0 || '林三心' // 林三心
const b = '' || '林三心' // 林三心
const c = false || '林三心' // 林三心
const d = undefined || '林三心' // 林三心
const e = null || '林三心' // 林三心