ES6+ 的必考集合,你都會了嗎?
點(diǎn)擊上方 三分鐘學(xué)前端,關(guān)注公眾號
回復(fù)交流,加入前端編程面試算法每日一題
我最常用的
ES6 的特性是使用最多的,包括類、模塊化、箭頭函數(shù)、函數(shù)參數(shù)默認(rèn)值、模板字符串、解構(gòu)賦值、延展操作符、Promise、let 與 const等等,這部分已經(jīng)是開發(fā)必備了,沒什么好說的
另外還有:
ES7 的 Array.prototype.includes()ES8 的 async/await 、String padding: padStart()和padEnd()、Object.values()ES9 的 Rest/Spread 屬性、for await of、 Promise.finally()ES10 的 Array.prototype.flat()、Array.prototype.flatMap()、String的trimStart()trimEnd()ES11 的 Promise.allSettled、空值處理及可選鏈ES12 的邏輯賦值操作符、數(shù)字分隔符、 Promise.any()
最有用的
ES6 的特性都很有用,ES7-ES11中,我比較感興趣的是:
ES8 的 async/await ES9 的 for await of ES11 的 Promise.allSettled、ES9 的Promise.finally()、ES12 的Promise.any()還有常用的邏輯操作:邏輯賦值操作符、數(shù)字分隔符、空值處理及可選鏈等都很大的簡潔優(yōu)化了我們的代碼
其中,async/await 異步終極解決方案,for await of 異步串行,Promise.allSettled 解決了 Promise.all 的只要一個(gè)請求失敗了就會拋出錯(cuò)誤的問題,當(dāng)我們一次發(fā)起多個(gè)請求時(shí),所有結(jié)果都能返回,無論成功或失敗,等等等,不了解的可以往下查找
下面列一下所有的特性,查漏補(bǔ)缺
ES6(ES2015)
類 模塊化 箭頭函數(shù) 函數(shù)參數(shù)默認(rèn)值 模板字符串 解構(gòu)賦值 擴(kuò)展操作符 對象屬性簡寫 Promise let 與 const
具體不再冗余介紹,這個(gè)屬于前端基礎(chǔ)
ES7(ES2016)
Array.prototype.includes()
指數(shù)操作符
Array.prototype.includes()
[1, 2].includes(1) // true
指數(shù)操作符
2**5 // 32
ES8(ES2017)
async/await Object.values() Object.entries() String padding: padStart()和padEnd(),填充字符串達(dá)到當(dāng)前長度Object.getOwnPropertyDescriptors() 函數(shù)參數(shù)列表結(jié)尾允許逗號 SharedArrayBuffer對象 Atomics對象
async/await
異步終極解決方案
async getInfo(){
const res = await api.getData()
// ...
}
Object.values()
Object.values({a: 1, b: 2, c: 3})
// [1, 2, 3]
Object.entries()
Object.values({a: 1, b: 2, c: 3})
// [["a", 1], ["b", 2], ["c", 3]]
String padding: padStart()和padEnd()
padStart() 方法用另一個(gè)字符串填充當(dāng)前字符串(如果需要的話,會重復(fù)多次),以便產(chǎn)生的字符串達(dá)到給定的長度。從當(dāng)前字符串的左側(cè)開始填充
// padStart
'sister'.padStart(7, '0') // "0sister"
// padEnd
'sister'.padEnd(7, '0') // "sister0"
Object.getOwnPropertyDescriptors()
Object.getOwnPropertyDescriptors() 函數(shù)用來獲取一個(gè)對象的所有自身屬性的描述符,如果沒有任何自身屬性,則返回空對象
函數(shù)參數(shù)列表結(jié)尾允許逗號
這是一個(gè)不痛不癢的更新,主要作用是方便使用git進(jìn)行多人協(xié)作開發(fā)時(shí)修改同一個(gè)函數(shù)減少不必要的行變更
ES9(ES2018)
異步迭代(for await of) Promise.finally() Rest/Spread 屬性 新的正則表達(dá)式特性 正則表達(dá)式反向斷言(lookbehind) 正則表達(dá)式dotAll模式 正則表達(dá)式命名捕獲組(Regular Expression Named Capture Groups) 正則表達(dá)式 Unicode 轉(zhuǎn)義 非轉(zhuǎn)義序列的模板字符串
異步迭代(for await of)
await 可以和 for…of 循環(huán)一起使用,以串行的方式運(yùn)行異步操作
async function getInfos(arr) {
for await (let i of arr) {
getData(i)
}
}
Promise.finally()
無論 Promise 運(yùn)行成功還是失敗,都會運(yùn)行 finally
function getInfos() {
getData1()
.then(getData2)
.catch(err => {
console.log(err);
})
.finally(() => {
// ...
});
}
Rest/Spread 屬性
const values = [1, 2, 3]
console.log( Math.min(...values) ) // 1
新的正則表達(dá)式特性
正則表達(dá)式命名捕獲組(Regular Expression Named Capture Groups)
在一些正則表達(dá)式模式中,使用數(shù)字進(jìn)行匹配可能會令人混淆。例如,使用正則表達(dá)式 /(\d{4})-(\d{2})-(\d{2})/ 來匹配日期。因?yàn)槊朗接⒄Z中的日期表示法和英式英語中的日期表示法不同,所以很難區(qū)分哪一組表示日期,哪一組表示月份
const re = /(\d{4})-(\d{2})-(\d{2})/;
const match= re.exec('2019-01-01');
console.log(match[0]); // → 2019-01-01
console.log(match[1]); // → 2019
console.log(match[2]); // → 01
console.log(match[3]); // → 01
ES9引入了命名捕獲組,允許為每一個(gè)組匹配指定一個(gè)名字,既便于閱讀代碼,又便于引用。
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = re.exec('2019-01-01');
console.log(match.groups); // → {year: "2019", month: "01", day: "01"}
console.log(match.groups.year); // → 2019
console.log(match.groups.month); // → 01
console.log(match.groups.day); // → 01
正則表達(dá)式反向斷言(lookbehind)
let test = 'hello sisteran'
console.log(test.match(/(?<=sisteran\s)hello/))
// ["hello", index: 6, input: "sisteran hello", groups: undefined]
正則表達(dá)式dotAll模式
正則表達(dá)式中,點(diǎn)(.)是一個(gè)特殊字符,代表任意的單個(gè)字符,但是有兩個(gè)例外。一個(gè)是四個(gè)字節(jié)的 UTF-16 字符,這個(gè)可以用u修飾符解決;另一個(gè)是行終止符,如換行符(\n)或回車符(\r),這個(gè)可以通過ES9的s(dotAll)flag,在原正則表達(dá)式基礎(chǔ)上添加s表示:
console.log(/foo.bar/.test('foo\nbar')) // false
console.log(/foo.bar/s.test('foo\nbar')) // true
那如何判斷當(dāng)前正則是否使用了 dotAll 模式呢?
const re = /foo.bar/s // Or, `const re = new RegExp('foo.bar', 's');`.
console.log(re.test('foo\nbar')) // true
console.log(re.dotAll) // true
console.log(re.flags) // 's'
正則表達(dá)式 Unicode 轉(zhuǎn)義
引入了一種新的類的寫法\p{...}和\P{...},允許正則表達(dá)式匹配符合 Unicode 某種屬性的所有字符
非轉(zhuǎn)義序列的模板字符串
之前,\u開始一個(gè) unicode 轉(zhuǎn)義,\x開始一個(gè)十六進(jìn)制轉(zhuǎn)義,\后跟一個(gè)數(shù)字開始一個(gè)八進(jìn)制轉(zhuǎn)義。這使得創(chuàng)建特定的字符串變得不可能,例如Windows文件路徑 C:\uuu\xxx\111。
更多細(xì)節(jié)參考模板字符串。
ES10(ES2019)
新增了Array的 flat()方法和flatMap()方法新增了String的 trimStart()方法和trimEnd()方法Object.fromEntries()Symbol.prototype.description()Function.prototype.toString()現(xiàn)在返回精確字符,包括空格和注釋簡化 try {} catch {},修改catch綁定
新增了Array的 flat() 方法和 flatMap() 方法
flat() 和 flatMap() 本質(zhì)上就是是歸納(reduce) 與 合并(concat)的操作
[1, 2, [3, 4]].flat(Infinity); // [1, 2, 3, 4]
[1, 2, 3, 4].flatMap(a => [a**2]); // [1, 4, 9, 16]
新增了String的 trimStart() 方法和 trimEnd() 方法
分別去除字符串首尾空白字符
Object.fromEntries()
返回一個(gè)給定對象自身可枚舉屬性的鍵值對數(shù)組
Object.fromEntries() 是 Object.entries() 的反轉(zhuǎn)
通過 Object.fromEntries, 可以將 Map 轉(zhuǎn)化為 Object:
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
const obj = Object.fromEntries(map);
console.log(obj); // { foo: "bar", baz: 42 }
通過 Object.fromEntries, 可以將 Array 轉(zhuǎn)化為 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 對象的可選描述的字符串。
Symbol('description').description; // 'description'
Function.prototype.toString() 現(xiàn)在返回精確字符,包括空格和注釋
function /* comment */ foo /* another comment */() {}
// 之前不會打印注釋部分
console.log(foo.toString()); // function foo(){}
// ES2019 會把注釋一同打印
console.log(foo.toString()); // function /* comment */ foo /* another comment */ (){}
// 箭頭函數(shù)
const bar /* comment */ = /* another comment */ () => {};
console.log(bar.toString()); // () => {}
簡化 try {} catch {} ,修改 catch 綁定
try {} catch(e) {}
現(xiàn)在是
try {} catch {}
ES11(ES2020)
Promise.allSettled()可選鏈(Optional chaining) 空值合并運(yùn)算符(Nullish coalescing Operator) import()globalThisBigIntString.prototype.matchAll
Promise.allSettled
與 Promise.all 不同的是,它會返回所有的 promise 結(jié)果
const promise1 = Promise.resolve('hello')
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 200, 'problem'))
Promise.allSettled([promise1, promise2])
.then((values) => {
console.log(values)
})

可選鏈(Optional chaining)
可選鏈 可讓我們在查詢具有多層級的對象時(shí),不再需要進(jìn)行冗余的各種前置校驗(yàn)。
var name = user && user.info && user.info.name;
又或是這種
var age = user && user.info && user.info.getAge && user.info.getAge();
很容易命中 Uncaught TypeError: Cannot read property...
用了 Optional Chaining ,上面代碼會變成
var name = user?.info?.name;
var age = user?.info?.getAge?.();
空值合并運(yùn)算符(Nullish coalescing Operator)
設(shè)置一個(gè)默認(rèn)的值
var level = user.data.level || '暫無等級';
來看看用空值合并運(yùn)算符如何處理
// {
// "level": 0
// }
var level = user.level ?? '暫無等級'; // level -> 0
// {
// "an_other_field": 0
// }
var level = user.level ?? '暫無等級'; // level -> '暫無等級'
import()
按需加載
globalThis
globalThis 目的就是提供一種標(biāo)準(zhǔn)化方式訪問全局對象,有了 globalThis 后,你可以在任意上下文,任意時(shí)刻都能獲取到全局對象
BigInt
BigInt 是一種內(nèi)置對象,它提供了一種方法來表示大于 253 - 1 的整數(shù)。這原本是 Javascript中可以用 Number 表示的最大數(shù)字。BigInt 可以表示任意大的整數(shù)
String.prototype.matchAll()
matchAll() 方法返回一個(gè)包含所有匹配正則表達(dá)式及分組捕獲結(jié)果的迭代器
ES12(ES2021)
String.prototype.replaceAll() Promise.any() WeakRef 邏輯賦值操作符(Logical Assignment Operators) 數(shù)字分隔符(Numeric separators)
String.prototype.replaceAll()
返回一個(gè)全新的字符串,所有符合匹配規(guī)則的字符都將被替換掉
const str = 'sisteran';
str.replaceAll('s', 'q'); // 'qiqteran'
Promise.any()
Promise.any() 接收一個(gè)Promise可迭代對象(例如數(shù)組),
只要其中的一個(gè) promise 成功,就返回那個(gè)已經(jīng)成功的 promise 如果可迭代對象中沒有一個(gè) promise 成功(即所有的 promises 都失敗/拒絕),就返回一個(gè)失敗的 promise
WeakRef
使用WeakRefs的Class類創(chuàng)建對對象的弱引用(對對象的弱引用是指當(dāng)該對象應(yīng)該被GC回收時(shí)不會阻止GC的回收行為)
邏輯賦值操作符(Logical Assignment Operators)
a ||= b
//等價(jià)于
a = a || (a = b)
a &&= b
//等價(jià)于
a = a && (a = b)
a ??= b
//等價(jià)于
a = a ?? (a = b)
數(shù)字分隔符(Numeric separators)
const money = 1_000_000_000 // 1000000000
參考:
種草 ES2020 新特性:https://juejin.cn/post/6844904034780839944 ES6、ES7、ES8、ES9、ES10新特性一覽:https://juejin.cn/post/6844903811622912014 盤點(diǎn)ES7、ES8、ES9、ES10新特性:https://juejin.cn/post/6844904018834096142
來自:https://github.com/sisterAn/blog

