主要新特性:
Array.prototype.{flat,flatMap}
Object.fromEntries
次要新功能:
String.prototype.{trimStart,trimEnd}
Symbol.prototype.description
- 可選的
catch
綁定 Array.prototype.sort()
主要是內(nèi)部的變化:
從 V8 v7.3 / Chrome 73 開始簿煌,所有這些 ES2019 功能都默認可用隆箩。
Array.prototype.flat() 和 Array.prototype.flatMap()
flat
方法創(chuàng)建一個新數(shù)組,其中所有子數(shù)組元素遞歸連接到該數(shù)組中,直到指定的深度。默認深度為 1荞雏。
const arr1 = [1, 2, [3, 4]]
arr1.flat() // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]]
arr2.flat() // [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]]
arr3.flat(2) // [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
arr4.flat(Infinity) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
更多實現(xiàn)技巧可查閱數(shù)組扁平化况毅。
flatMap()
方法首先使用 map
方法映射每個元素梭稚,然后將結(jié)果壓縮成一個新數(shù)組箱玷。它與 map
連著深度值為 1 的 flat
幾乎相同怨规,但 flatMap
通常在合并成一種方法的效率稍微高一些陌宿。
const arr = [1, 2, 3, 4]
arr.flatMap(x => [x * 2]) // [2, 4, 6, 8]
// 只有一層是扁平的
arr.flatMap(x => [[x * 2]]) // [[2], [4], [6], [8]]
Object.fromEntries()
Object.fromEntries()
從給定的鍵值對構(gòu)建一個對象锡足。
它接收一個鍵值對列表,并返回一個對象壳坪,其屬性由條目給出舶得。它的功能與 Object.entries()
相反。
const entries = new Map([
['apple', 'origin'],
['grapes', 'peach']
])
console.log(Object.fromEntries(entries)) // { apple: 'origin', grapes: 'peach' }
我們可以看到爽蝴,當我們向 fromEntries()
函數(shù)提供一個映射(它成對存儲值)時沐批,我們得到了一個對象,該對象與映射中的相應鍵值對相同蝎亚。
String.prototype.trimStart() 和 String.prototype.trimEnd()
它原本的名稱為 trimRight
和 trimLeft
九孩,但在 ES2019 中,名稱被更改為 trimStart
和 trimEnd
发框,以使它看起來更直觀躺彬。
trimStart
修剪給定字符串的開頭。trimEnd
修剪給定字符串的結(jié)尾梅惯。
let message = ' Hello '
message.trimStart() // "Hello "
message.trimEnd() // "Hello"
Symbol.prototype.description
當我們在 JS 中創(chuàng)建一個 Symbol
時宪拥,可以指定一個描述,用于以后的調(diào)試铣减。取回這個描述的過程有點乏味她君。我們必須重新構(gòu)造 Symbol
,并借助 toString()
方法訪問描述葫哗。
ES10 添加了一個名為 description
的新只讀屬性缔刹,該屬性返回 Symbol
的描述。
const symbol = Symbol('This is a Symbol')
console.log(symbol.toString()) // Symbol(This is a Symbol)
console.log(symbol.description) // This is a Symbol
我們可以看到劣针,我們直接使用 description
屬性得到 Symbol
的描述校镐。
可選 catch
綁定
在 ES10 之前,語法迫使我們?yōu)?catch
子句綁定一個異常變量酿秸,不管它是否必要灭翔。很多時候可以注意到,catch
塊只是多余的。ES10 提案使我們能夠完全忽略變量肝箱,讓我們少關(guān)心一件事哄褒。
try {
const data = JSON.parse(obj)
return true
} catch {
return false
}
https://blog.logrocket.com/new-es2019-javascript-features-every-developer-should-be-excited-about/
https://blog.logrocket.com/optional-chaining-and-nullish-coalescing-in-javascript/
https://blog.logrocket.com/6-cutting-edge-javascript-features-you-can-use-today/
https://www.freecodecamp.org/news/a-taste-of-whats-new-in-es10-68d28ba22f92/
https://blog.csdn.net/qq_34586870/article/details/89515336