JavaScript高級(jí)系列(十五) - ES6~ES13-ES7~ES12知識(shí)點(diǎn)
共 9365字,需瀏覽 19分鐘
·
2024-04-16 11:08
這個(gè)章節(jié)中我們講解ES7~ES12中重要的核心語法。
一. ES7知識(shí)點(diǎn)
1.1. Array Includes
在ES7之前,如果我們想判斷一個(gè)數(shù)組中是否包含某個(gè)元素,需要通過 indexOf 獲取結(jié)果,并且判斷是否為 -1。
在ES7中,我們可以通過includes來判斷一個(gè)數(shù)組中是否包含一個(gè)指定的元素,根據(jù)情況,如果包含則返回 true,否則返回false。
語法如下:
arr.includes(valueToFind[, fromIndex])
const names = ["abc", "cba", "nba", "why"]
if (names.indexOf("why") !== -1) {
console.log("包含why")
}
if (names.includes("why")) {
console.log("包含why")
}
if (names.includes("why", 4)) {
console.log("包含why")
}
并且對(duì)于NaN、undefined的查找,includes要好于indexOf:
const names = ["abc", "cba", "nba", "why", NaN]
console.log(names.indexOf(NaN)) // -1
console.log(names.includes(NaN)) // true
1.2. 平方運(yùn)算符
在ES7之前,計(jì)算數(shù)字的平方需要通過 Math.pow 方法來完成。
在ES7中,增加了 ** 運(yùn)算符,可以對(duì)數(shù)字來計(jì)算平方。
const result1 = Math.pow(3, 3)
const result2 = 3 ** 3
console.log(result1, result2)
二. ES8知識(shí)點(diǎn)
2.1. Object values
之前我們可以通過 Object.keys 獲取一個(gè)對(duì)象所有的key,在ES8中提供了 Object.values 來獲取所有的value值:
const obj = {
name: "why",
age: 18,
height: 1.88
}
console.log(Object.values(obj)) // [ 'why', 18, 1.88 ]
// 如果傳入一個(gè)字符串
console.log(Object.values("abc")) // [ 'a', 'b', 'c' ]
2.2. Object entries
通過Object.entries 可以獲取到一個(gè)數(shù)組,數(shù)組中會(huì)存放可枚舉屬性的鍵值對(duì)數(shù)組。
const obj = {
name: "why",
age: 18,
height: 1.88
}
console.log(Object.entries(obj)) // [ [ 'name', 'why' ], [ 'age', 18 ], [ 'height', 1.88 ] ]
for (const entry of Object.entries(obj)) {
const [key, value] = entry
console.log(key, value)
}
// 如果是一個(gè)數(shù)組
console.log(Object.entries(["abc", "cba", "nba"])) // [ [ '0', 'abc' ], [ '1', 'cba' ], [ '2', 'nba' ] ]
// 如果是一個(gè)字符串
console.log(Object.entries("abc")) // [ [ '0', 'a' ], [ '1', 'b' ], [ '2', 'c' ] ]
2.3. Object Descriptors
ES8中增加了另一個(gè)對(duì)對(duì)象的操作是 Object.getOwnPropertyDescriptors ,這個(gè)在之前已經(jīng)講過了,這里不再重復(fù)。
2.4. String Padding
某些字符串我們需要對(duì)其進(jìn)行前后的填充,來實(shí)現(xiàn)某種格式化效果,ES8中增加了 padStart 和 padEnd 方法,分別是對(duì)字符串的首尾進(jìn)行填充的。
const message = "Hello World"
console.log(message.padStart(15, "a")) // aaaaHello World
console.log(message.padEnd(15, "b")) // Hello Worldbbbb
我們簡(jiǎn)單具一個(gè)應(yīng)用場(chǎng)景:比如需要對(duì)身份證、銀行卡的前面位數(shù)進(jìn)行隱藏:
const cardNumber = "3242523524256245223879"
const lastFourNumber = cardNumber.slice(-4)
const finalCardNumber = lastFourNumber.padStart(cardNumber.length, "*")
console.log(finalCardNumber) // ******************3879
2.5. Trailing Commas
在ES8中,我們?cè)试S在函數(shù)定義和調(diào)用時(shí)多加一個(gè)逗號(hào):
function foo(a, b,) {
console.log(a, b)
}
foo(10, 20,)
三. ES9知識(shí)點(diǎn)
ES9中新增的知識(shí)點(diǎn)主要有三個(gè):
3.1. Async iterators
后續(xù)迭代器講解
3.2. Object spread operators;
前面講過了
3.3. Promise finally;
后續(xù)講Promise講解
四. ES10知識(shí)點(diǎn)
4.1. flat flatMap
flat() 方法會(huì)按照一個(gè)可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個(gè)新數(shù)組返回。
const nums = [10, 20, [5, 8], [[2, 3], [9, 22]], 100]
const newNums1 = nums.flat(1)
const newNums2 = nums.flat(2)
// [ 10, 20, 5, 8, [ 2, 3 ], [ 9, 22 ], 100 ]
console.log(newNums1)
// [ 10, 20, 5, 8, 2, 3, 9, 22, 100 ]
console.log(newNums2)
flatMap() 方法首先使用映射函數(shù)映射每個(gè)元素,然后將結(jié)果壓縮成一個(gè)新數(shù)組。
-
注意一:flatMap是先進(jìn)行map操作,再做flat的操作; -
注意二:flatMap中的flat相當(dāng)于深度為1;
const messages = ["Hello World", "你好啊 李銀河", "my name is why"]
const newMessages = messages.flatMap(item => {
return item.split(" ")
})
console.log(newMessages)
4.2. Object formEntries
在前面,我們可以通過 Object.entries 將一個(gè)對(duì)象轉(zhuǎn)換成 entries,那么如果我們有一個(gè)entries了,如何將其轉(zhuǎn)換成對(duì)象呢?
-
ES10提供了 Object.formEntries來完成轉(zhuǎn)換:
const obj = {
name: "why",
age: 18,
height: 1.88
}
const entries = Object.entries(obj)
console.log(entries)
const info = Object.fromEntries(entries)
console.log(info)
那么這個(gè)方法有什么應(yīng)用場(chǎng)景呢?
const paramsString = 'name=why&age=18&height=1.88'
const searchParams = new URLSearchParams(paramsString)
for (const param of searchParams) {
console.log(param)
}
const searchObj = Object.fromEntries(searchParams)
console.log(searchObj)
4.3. trimStart trimEnd
去除一個(gè)字符串首尾的空格,我們可以通過trim方法,如果單獨(dú)去除前面或者后面呢?
-
ES10中給我們提供了trimStart和trimEnd;
const message = " Hello World "
console.log(message.trim())
console.log(message.trimStart())
console.log(message.trimEnd())
4.4. Symbol description
已經(jīng)講過了(講解Symbol的時(shí)候)
4.5. Optional catch binding
后面講解try cach講解
五. ES11知識(shí)點(diǎn)
5.1. BigInt
在早期的JavaScript中,我們不能正確的表示過大的數(shù)字:
-
大于MAX_SAFE_INTEGER的數(shù)值,表示的可能是不正確的。
const maxInt = Number.MAX_SAFE_INTEGER
console.log(maxInt)
// 大于MAX_SAFE_INTEGER值的一些數(shù)值,無法正確的表示
console.log(maxInt + 1) // 9007199254740992
console.log(maxInt + 2) // 9007199254740992
那么ES11中,引入了新的數(shù)據(jù)類型BigInt,用于表示大的整數(shù):
-
BitInt的表示方法是在數(shù)值的后面加上n
const bigInt = 9007199254740991n
console.log(bigInt + 1n)
console.log(bigInt + 2n)
BigInt可以將其他數(shù)據(jù)類型轉(zhuǎn)成BigInt:
const bigInt1 = BigInt(10)
console.log(bigInt1) // 10n
const int1 = Number(bigInt1)
console.log(int1)
5.2. Dynamic Import
后續(xù)ES Module模塊化中講解。
5.3. Nullish Coalescing Operator
ES11,Nullish Coalescing Operator增加了空值合并操作符:
const foo = ""
const result1 = foo || "默認(rèn)值"
const result2 = foo ?? "默認(rèn)值"
console.log(result1) // 默認(rèn)值
console.log(result2) // ""
5.4. Optional Chaining
可選鏈也是ES11中新增一個(gè)特性,主要作用是讓我們的代碼在進(jìn)行null和undefined判斷時(shí)更加清晰和簡(jiǎn)潔:
const obj = {
friend: {
girlFriend: {
name: "lucy"
}
}
}
if (obj.friend && obj.friend.girlFriend) {
console.log(obj.friend.girlFriend.name)
}
可選鏈可以幫助我們?cè)谟兄档那闆r下返回對(duì)應(yīng)的值,沒有值的情況下返回undefined:
// 可選鏈的方式
console.log(obj.friend?.girlFriend?.name)
5.5. Promise.allSettled
后續(xù)講Promise的時(shí)候講解。
5.6. Global This
在之前我們希望獲取JavaScript環(huán)境的全局對(duì)象,不同的環(huán)境獲取的方式是不一樣的
-
比如在瀏覽器中可以通過this、window來獲取; -
比如在Node中我們需要通過global來獲取;
那么在ES11中對(duì)獲取全局對(duì)象進(jìn)行了統(tǒng)一的規(guī)范:globalThis
console.log(globalThis)
console.log(this) // 瀏覽器上
console.log(global) // Node中
5.7. import meta
后續(xù)ES Module模塊化中講解。
5.8. for..in標(biāo)準(zhǔn)化
在ES11之前,雖然很多瀏覽器支持for...in來遍歷對(duì)象類型,但是并沒有被ECMA標(biāo)準(zhǔn)化。
在ES11中,對(duì)其進(jìn)行了標(biāo)準(zhǔn)化,for...in是用于遍歷對(duì)象的key的:
const obj = {
name: "why",
age: 18,
height: 1.88
}
for (const key in obj) {
console.log(key)
}
六. ES12知識(shí)點(diǎn)
6.1. FinalizationRegistry
FinalizationRegistry 對(duì)象可以讓你在對(duì)象被垃圾回收時(shí)請(qǐng)求一個(gè)回調(diào)。
-
FinalizationRegistry提供了這樣的一種方法:當(dāng)一個(gè)在注冊(cè)表中注冊(cè)的對(duì)象被回收時(shí),請(qǐng)求在某個(gè)時(shí)間點(diǎn)上調(diào)用一個(gè)清理回調(diào)。(清理回調(diào)有時(shí)被稱為 finalizer ); -
你可以通過調(diào)用 register方法,注冊(cè)任何你想要清理回調(diào)的對(duì)象,傳入該對(duì)象和所含的值;
let obj = { name: "why" }
const registry = new FinalizationRegistry(value => {
console.log("對(duì)象被銷毀了", value)
})
registry.register(obj, "obj")
obj = null
6.2. WeakRefs
如果我們默認(rèn)將一個(gè)對(duì)象賦值給另外一個(gè)引用,那么這個(gè)引用是一個(gè)強(qiáng)引用:
-
如果我們希望是一個(gè)弱引用的話,可以使用WeakRef;
let obj = { name: "why" }
let info = new WeakRef(obj)
const registry = new FinalizationRegistry(value => {
console.log("對(duì)象被銷毀了", value)
})
registry.register(obj, "obj")
obj = null
6.3. logical assignment operators
// 1.邏輯或運(yùn)算符
let message = ""
// message = message || "hello world"
message ||= "Hello World"
console.log(message)
let obj = {
name: "why"
}
// 2.邏輯與操作符
// obj = obj && obj.foo()
obj &&= obj.name
console.log(obj)
// 3.邏輯空運(yùn)算符
let foo = null
foo ??= "默認(rèn)值"
console.log(foo)
6.4. Numeric Separator
// ES2021新增特性
const num5 = 100_000_000
七. ES13知識(shí)點(diǎn)
更新ing(隨著視頻一起更新)
