ES6 ESNext新增API

162 阅读6分钟

ES7新特性(2016)

Array.prototype.includes()

  • includes() 判断一个数组是否包含一个指定的值

    • 包含则返回 true,否则返回 false
  • includes 函数与 indexOf 函数功能基本等价

    arr.includes(x)
    arr.indexOf(x) >= 0
    

指数操作符

  • ** 具有与 Math.pow(..)等效的计算结果

ES8 新特性(2017)

async/await

async function process(array) {
  for await (let i of array) {
    doSomething(i)
  }
}

Object.values()

  • 返回的是Object自身属性的所有值,不包括继承的值

  • 遍历 obj 的所有值

const obj = {a: 1, b: 2, c: 3}

// ES7
const vals = Object.keys(obj).map((key) => obj[key])
console.log(vals)

// ES8
values = Object.values(obj1)
console.log(values)

Object.entries()

  • 返回一个给定对象自身可枚举属性的键值对的数组
// ES7
Object.keys(obj).forEach((key) => {
  console.log('key:' + key + ' value:' + obj[key])
})
//key:b value:2

// ES8
for (let [key, value] of Object.entries(obj1)) {
  console.log(`key: $ {key},value: $ {value}`)
}
//key:b value:2

String padding

  • String.padStart(targetLength,[padString])

  • 允许将空字符串或其他字符串添加到原始字符串的开头或结尾

  • targetLength:当前字符串需要填充到的目标长度

    • 如果这个数值小于当前字符串的长度,则返回当前字符串本身
  • padString:(可选)填充字符串

    • 如果字符串太长,使填充后的字符串长度超过了目标长度,则只保留最左侧的部分,其他部分会被截断,此参数的缺省值为 " "
console.log('0.0'.padStart(4, '10'))
// 10.0

console.log('0.0'.padStart(20))
// 0.0

函数参数列表结尾允许逗号

Object.getOwnPropertyDescriptors()

  • 获取一个对象的所有自身属性的描述符

    • 如果没有任何自身属性,则返回空对象
const obj2 = {
  name: 'Jine',
  get age() {
    return '18'
  },
}
Object.getOwnPropertyDescriptors(obj2)
//   age: {
//     enumerable: true,
//     set: undefined
//   name: {
//     enumerable: true,
//        writable:true
// }

SharedArrayBuffer对象

  • 通用的,固定长度的原始二进制数据缓冲区,类似于 ArrayBuffer 对象

    • 它们都可以用来在共享内存(shared memory)上创建视图

    • 不同的是,SharedArrayBuffer 不能被分离

new SharedArrayBuffer(length)

ES9新特性(2018)

异步迭代

  • 像常规迭代器,除了 next()方法返回一个Promise

  • await可以和 for...of循环一起使用,以串行的方式运行异步操作

async function process(array) {
  for await (let i of array) {
    doSomething(i)
  }
}

Promise.finally()

  • .finally()允许你指定最终的逻辑

    • 清除,删除对话,关闭数据库连接等
function doSomething() {
  doSomething1()
    .then(doSomething2)
    .then(doSomething3)
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {})
}

Rest/Spread 属性

  • Rest参数语法允许将一个不定数量的参数表示为一个数组

    • 只能在声明的结尾处使用

    • 只适用于每个对象的顶层,如果对象中嵌套对象则无法适用

restParam(1, 2, 3, 4, 5)
function restParam(p1, p2, ...p3) {
  // p2 = 2
}
  • 展开操作符将数组转换成可传递给函数的单独参数

    • 可以在其他对象内使用

    • 浅拷贝

const values = [99, 100, -1, 48, 16]
console.log(Math.max(...values)) // 100

const myObject = {
  a: 1,
  b: 2,
  c: 3,
}
const { a, ...x } = myObject // x = { b: 2, c: 3 }

restParam({
  a: 1,
  b: 2,
  c: 3,
})
function restParam({ a, ...x }) {
  // x = { b: 2, c: 3 }
}

const obj1 = {
  a: 1,
  b: 2,
  c: 3,
}
const obj2 = { ...obj1, z: 26 }

qaq

正则表达式命名捕获组

正则表达式反向断言

正则表达式dotAll模式

正则表达式 Unicode 转义

ES10新特性(2019)

  • 行分隔符(U + 2028)和段分隔符(U + 2029)符号现在允许在字符串文字中,与JSON匹配

    • 以前使用它们会导致SyntaxError异常
  • 更加友好的 JSON.stringify

    • 如果输入 Unicode 格式但是超出范围的字符,在原先JSON.stringify返回格式错误的Unicode字符串。现在实现了一个改变JSON.stringify的第3阶段提案,因此它为其输出转义序列,使其成为有效Unicode(并以UTF-8表示)

新增Array的 flat()方法和 flatMap()方法

Array.prototype.flat()

  • 扁平化
var arr1 = [1, 2, [3, 4]]
arr1.flat()
var arr2 = [1, 2, [3, 4, [5, 6]]]
arr2.flat()
var arr3 = [1, 2, [3, 4, [5, 6]]]
arr3.flat(2) //使用 Infinity 作为深度,展开任意深度的嵌套数组arr3.flat(Infinity)
  • 去除数组的空项
var arr4 = [1, 2, , 4, 5]
arr4.flat()

Array.prototype.flatMap()

  • 使用映射函数映射每个元素,然后将结果压缩成一个新数组

  • 与 map 比较

var arr1 = [1, 2, 3, 4]
arr1.map((x) => [x * 2])
arr1.flatMap((x) => [x * 2]) // 只会将 flatMap 中的函数返回的数组 “压平” 一层arr1.flatMap(x => [[x * 2]])

Object.fromEntries()

  • Object.entries()与使用 for...in 循环遍历该对象时返回的顺序一致

    • 区别在于 for-in 循环也枚举原型链中的属性
  • 通过 Object.fromEntries, 可以将 Map 转化为 Object

const map = new Map([
  ['foo', 'bar'],
  ['baz', 42],
])
const obj = Object.fromEntries(map)
console.log(obj) // {foo: 'bar', baz: 42}
  • 通过 Object.fromEntries, 可以将 Array 转化为 Object
const arr = [
  ['0', 'a'],
  ['1', 'b'],
  ['2', 'c'],
]
const obj = Object.fromEntries(arr)
console.log(obj) // {0: 'a', 1: 'b', 2: 'c'}

Symbol.prototype.description

  • 直接访问 Symbol 描述
const sym = Symbol('The description')
assert.equal(String(sym), 'Symbol(The description)')
assert.equal(sym.description, 'The description')

String.prototype.matchAll

  • matchAll 会得到一个迭代器的返回值,配合 for...of, array spread, or Array.from() 可以更方便实现功能
const regexp = RegExp('foo*', 'g')
const str = 'table football, foosball'
let matches = str.matchAll(regexp)
for (const match of matches) {
  console.log(match)
} // Array [ "foo" ]
// Call matchAll again to create a new iteratormatches = str.matchAll(regexp); Array.from(matches, m => m[0]);
  • 更好的用于分组
var regexp = /t(e)(st(\d?))/g
var str = 'test1test2'
str.match(regexp)
let array = [...str.matchAll(regexp)]
array[0]
array[1]

Function.prototype.toString()现在返回精确字符,包括空格和注释

function /* comment */
foo() /* another comment */
{}
console.log(foo.toString())
// ES2019 会把注释一同打印console.log(foo.toString());
// 箭头函数const bar  = /* another comment */ () => {}; console.log(bar.toString())

修改 catch 绑定

  • ES10 提案使我们能够简单的把变量省略掉

  • try {} catch {}

新的基本数据类型 BigInt

ES11新特性(2020)

Promise.allSettled

  • 无论一个任务正常或者异常,都会返回对应的的状态(fulfilled / rejected)与结果(value / 拒因 reason),在 then 里面通过 filter 来过滤出想要的业务逻辑结果
Promise.allSettled([
  Promise.reject({
    code: 500,
    msg: '服务异常',
  }),
  Promise.resolve({
    code: 200,
    list: [],
  }),
  Promise.resolve({
    code: 200,
    list: [],
  }),
]).then((ret) => {
  /*         0: {status: "rejected", reason: {...}}     1: {status: "fulfilled", value: {...}}     2: {status: "fulfilled", value: {...}}     */
  // 过滤掉 rejected 状态,尽可能多的保证页面区域数据渲染
  // RenderContent(
  //   ret.filter((el) => {
  //     return el.status !== 'rejected'
  //   })
  // )
})

可选链

  • 可选链中的 ? 表示如果问号左边表达式有值, 就会继续查询问号后面的字段
var name = user && user.info && user.info.name
var age = user && user.info && user.info.getAge && user.info.getAge()

var name1 = user?.info?.name
var age1 = user?.info?.getAge?.()

空值合并运算符

var level
if (typeof user.level === 'number') {
  level = user.level
} else if (!user.level) {
  level = '暂无等级'
} else {
  level = user.level
}

// 空值合并运算符
// { //   "level": 0 // }
var level = `${user.level}级` ?? '暂无等级'
// level -> '0级'

// 空值合并运算符 与 可选链 相结合
var level = user.data?.level ?? '暂无等级'

dynamic-import

el.onclick = () => {
  import(` / path / current - logic.js`)
    .then((module) => {
      module.doSomthing()
    })
    .catch((err) => {
      // load error
    })
}

globalThis

  • 在任意上下文,任意时刻都能获取到全局对象
var getGlobal = function () {
  if (typeof self !== 'undefined') {
    return self
  }
  if (typeofwindow !== 'undefined') {
    returnwindow
  }
  if (typeof global !== 'undefined') {
    return global
  }
  thrownewError('unable to locate global object')
}
var globals = getGlobal() // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/globalThis

BigInt

  • 在整数字面量后面加n

  • 使用 BigInt 函数

  • 尽可能避免通过调用函数 BigInt 方式来实例化超大整型

    • 因为参数的字面量实际也是 Number 类型的一次实例化,超出安全范围的数字,可能会引起精度丢失
var bigIntNum = 9007199254740993n

var bigIntNum1 = BigInt(9007199254740)
var anOtherBigIntNum = BigInt('9007199254740993')

var bigNumRet = 9007199254740993n + 9007199254740993n
// -> -> 18014398509481986n bigNumRet.toString();
// -> '18014398509481986'

String.prototype.matchAll

  • 该方法会返回一个迭代器
var str = '<text>JS</text><text>正则</text>'
var allMatchs = str.matchAll(/<\w+>(.*?)<\/\w+>/g)
for (const match of allMatchs) {
  console.log(match)
}