每年都有一些新的屬性進入ECMA262標準,今年發布的ECMAScript2019/ES10同樣也有很多新的特性,本文將會挑選一些普通開發者會用到的新屬性進行深入的解讀。
Array.prototype.flat()
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. -- MDN
簡單來說flat這個函數就是按照一定的深度depth將一個深層次嵌套的數組拍扁, 例子:
const nestedArr = [1, 2, [3, 4, [5, 6, [7, [8], 9]]], 10]console.log(nestedArr.flat())// [1, 2, 3, 4, [5, 6, [7, [8], 9]], 10]console.log(nestedArr.flat(2))// [1, 2, 3, 4, 5, 6, [7, [8], 9], 10]console.log(nestedArr.flat(3))// [1, 2, 3, 4, 5, 6, 7, [8], 9, 10]console.log(nestedArr.flat(4))// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]console.log(nestedArr.flat(Infinity))// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
由上面的例子可以看出flat會按照指定的深度depth將一個數組扁平化,如果需要將數組完全拍扁變成一維數組,則指定depth為無限大,即是Infinity,相反如果不指定深度,其默認值是1。
Array.prototype.flatMap()
The flatMap() method first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient. -- MDN
簡單來說flatMap等于一個數組先調用完map函數再調用flat函數將其扁平化,扁平化的深度固定為1,先通過一個簡單的例子感受一下:
const myArr = [1, 2, 3]myArr .map(n => [n * n]) // [[1], [4], [9]] .flat() // [1, 4, 9]// 用flatMap可以一步到位myArr.flatMap(n => [n * n]) // [1, 4, 9]
從上面的例子來看flatMap如果只是將flat和map做了一個簡單的組合好像可有可無,其實不然,flatMap有個強大的功能是可以在map的時候添加和刪除元素,這個無論是map還是filter都沒有這個功能。
要想刪除某一個元素只需要在mapper函數里面返回一個空的數組[], 而增加元素只需在mapper函數里面返回一個長度大于1的數組,具體可以看下面的例子:
// 假如我們想要刪除掉原數組里面所有的負數,同時將單數轉換為一個復數和1const a = [5, 4, -3, 20, 17, -33, -4, 18]// |/ / x | | / x x |// [4,1, 4, 20, 16,1, 18]a.flatMap(n => (n < 0) ? []: // 刪除負數 (n % 2 == 0) ? [n] : // 保留復數 [n - 1, 1] // 單數變為一個復數和1)// [4, 1, 4, 20, 20, 16, 1, 18]
Object.fromEntries()
The Object.fromEntries() method transforms a list of key-value pairs into an object. --MDN
fromEntries方法將一個iterable對象返回的一系列鍵值對(key-value pairs)轉換為一個object。先看一個簡單的例子理解一下:
// key-value pairs數組const entriesArr = [['k1', 1], ['k2', 2]]console.log(Object.fromEntries(entriesArr)// {k1: 1, k2: 2}const entriesMap = new Map([ ['k1', 1], ['k2', 2]]) // {"k1" => 1, "k2" => 2}console.log(Object.fromEntries(entriesMap))// {k1: 1, k2: 2}
再來看一個自定義的iterable對象例子深入理解一下:
新聞熱點
疑難解答