# 常用的 ECMAScript 系列
# ES7(2016)
Array.prototype.includes()
指数操作符
Math.pow(2, 10)
2 ** 10
# ES8(2017)
Object.values()/Object.entries()
async/await
在字符串开头或结尾添加填充字符串达到当前长度
String.padStart(targetLength, [padString])
String.padEnd(targetLength, [padString])
Object.getOwnPropertyDescriptors()
函数参数列表结尾允许逗号
# ES9(2018)
- 异步迭代
async function process(array) {
for await (let i of array) {
doSomething(i)
}
}
Promise.finally()
正则表达式命名捕获组
const reDate = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/,
d = '2018-04-30',
usDate = d.replace(reDate, '$<month>-$<day>-$<year>')
console.log(usDate) // "04-30-2018"
- 对象 Rest 参数和展开操作符
const obj = {
a: 1,
b: 2,
c: 3
}
const { a, ...x } = obj
// a = 1
// x = { b: 2, c: 3 }
# ES10(2019)
- 数组扁平化
Array.flat()
Array.flatMap()
- 去除字符串首尾空白字符
String.trimStart()
String.trimEnd()
使用方法:
1、去除开头 和 结尾的空格
" 1 23 ".trim() => "1 23"
2、只去除开头 的空格
" 1 23 ".trimStart() => "1 23 "
3、只去除结尾的空格
" 1 23 ".trimEnd() => " 1 23"
- 修改 catch 绑定
try {
} catch (e) {}
// 现在是
try {
} catch {}
# ES11(2020)
1.空值处理
表达式在 ?? 的左侧 运算符求值为 undefined 或 null,返回其右侧。
let user = {
u1: 0,
u2: false,
u3: null,
u4: undefined
u5: '',
}
let u2 = user.u2 ?? '用户2' // false
let u3 = user.u3 ?? '用户3' // 用户3
let u4 = user.u4 ?? '用户4' // 用户4
let u5 = user.u5 ?? '用户5' // ''
2.可选链
?.用户检测不确定的中间节点
let user = {}
let u1 = user.childer.name // TypeError: Cannot read property 'name' of undefined
let u1 = user.childer?.name // undefined
3.新基本数据类型 BigInt
typeof 10;
⇨ 'number'
typeof 10n;
⇨ 'bigint'
4.globalThis
浏览器:window
worker:self
node:global
5.Promise.allSettled()
返回一个在给定的 promise 都已经 fulfilled 或 rejected 后的 promise,并带有一个对象数组,每个对象表示对应的 promise 结果
const promise1 = Promise.resolve(3)
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'))
const promises = [promise1, promise2]
Promise.allSettled(promises).then(results => results.forEach(result => console.log(result.status)))
// fulfilled
// rejected
# ES12(2021)
1.replaceAll
返回一个全新的字符串,所有符合匹配规则的字符都将被替换掉
const str = 'hello world'
str.replaceAll('l', '') // "heo word"
2.Promise.any
Promise.any() 接收一个 Promise 可迭代对象,只要其中的一个 promise 成功,就返回那个已经成功的 promise 。如果可迭代对象中没有一个 promise 成功(即所有的 promises 都失败/拒绝),就返回一个失败的 promise
3.数字分隔符
数字分隔符,可以在数字之间创建可视化分隔符,通过_下划线来分割数字,使数字更具可读性
const money = 1_000_000_000
//等价于
const money = 1000000000
1_000_000_000 === 1000000000 // true
4.逻辑运算符和赋值表达式
逻辑运算符和赋值表达式,新特性结合了逻辑运算符(&&,||,??)和赋值表达式而 JavaScript 已存在的 复合赋值运算符有:
a ||= b
//等价于
a = a || (a = b)
a &&= b
//等价于
a = a && (a = b)
a ??= b
//等价于
a = a ?? (a = b)