ES使用频次高的新特性

153 阅读1分钟

ES7(2016)

1 includes() 方法用来判断一个数组/字符串是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false

1.1 Array.prototype.includes()

1.2 String.prototype.includes()

includes 函数与 indexOf 函数很相似,下面两个表达式是等价的:

arr.includes(x) // 返回true or false
arr.indexOf(x) >= 0

2 指数操作符

指数运算符**,效果同Math.pow()

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

ES9(2018)

3 Promise.finally()

一个Promise调用链要么成功到达最后一个.then(),要么失败触发.catch()。在某些情况下,你想要在无论Promise运行成功还是失败,运行相同的代码,例如清除,删除对话,关闭数据库连接等。

function doSomething() {
  doSomething1()
  .then(doSomething2)
  .then(doSomething3)
  .catch(err => {
    console.log(err);
  })
  .finally(() => {
    // finish here!
  });
}

参考:juejin.cn/post/684490…