ES10 可以使用几个新特性
在JavaScript中,將數(shù)據(jù)從一種格式轉(zhuǎn)換為另一種格式非常常見。
Object.entrie()方法
為了便于將對象轉(zhuǎn)換為數(shù)組,ES2017引入了Object.entrie()方法。 此方法將對象作為參數(shù),并以[key,value]的形式返回對象自己的可枚舉字符串鍵控屬性對的數(shù)組。 例如:
const obj = {one: 1, two: 2, three: 3};console.log(Object.entries(obj)); // => [["one", 1], ["two", 2], ["three", 3]]Object.fromEntries()方法
此靜態(tài)方法允許你輕松地將鍵值對列表轉(zhuǎn)換為對象:
const myArray = [['one', 1], ['two', 2], ['three', 3]]; const obj = Object.fromEntries(myArray);console.log(obj); // => {one: 1, two: 2, three: 3}這個方法主要是針對,一維數(shù)組,多維數(shù)據(jù)需要另想辦法。
trimStart() and trimEnd()
trimStart()和trimEnd()方法在實現(xiàn)與trimLeft()和trimRight()相同。這些方法目前處于第4階段,將被添加到規(guī)范中,以便與padStart()和padEnd()保持一致,來看一些例子:
const str = " string ";// es2019 console.log(str.trimStart()); // => "string " console.log(str.trimEnd()); // => " string"// 相同結(jié)果 console.log(str.trimLeft()); // => "string " console.log(str.trimRight()); // => " string"flat() and flatMap()
flat() 方法可以將多維數(shù)組展平成一維數(shù)組
const arr = ['a', 'b', ['c', 'd']]; const flattened = arr.flat();console.log(flattened); // => ["a", "b", "c", "d"]如果提供的數(shù)組中有空值,它們會被丟棄:
const arr = ['a', , , 'b', ['c', 'd']]; const flattened = arr.flat();console.log(flattened); // => ["a", "b", "c", "d"]flat() 還接受一個可選參數(shù),該參數(shù)指定嵌套數(shù)組應(yīng)該被展平的級別數(shù)。 如果未提供參數(shù),則將使用默認(rèn)值1:
const arr = [10, [20, [30]]];console.log(arr.flat()); // => [10, 20, [30]] console.log(arr.flat(1)); // => [10, 20, [30]] console.log(arr.flat(2)); // => [10, 20, 30]flatMap() 方法將map()和flat()組合成一個方法。 它首先使用提供的函數(shù)的返回值創(chuàng)建一個新數(shù)組,然后連接該數(shù)組的所有子數(shù)組元素。 來個例子:
const arr = [4.25, 19.99, 25.5];console.log(arr.map(value => [Math.round(value)])); // => [[4], [20], [26]]console.log(arr.flatMap(value => [Math.round(value)])); // => [4, 20, 26]數(shù)組將被展平的深度級別為1.如果要從結(jié)果中刪除項目,只需返回一個空數(shù)組:
const arr = [[7.1], [8.1], [9.1], [10.1], [11.1]];// do not include items bigger than 9 arr.flatMap(value => {if (value >= 10) {return [];} else {return Math.round(value);} }); // returns: // => [7, 8, 9]可選的 catch
以前的寫法
try {// 使用瀏覽器可能尚未實現(xiàn)的功能 } catch (unused) {// 這里回調(diào)函數(shù)中已經(jīng)幫我們處理好的錯誤 }此代碼中的catch回調(diào)的信息并沒有用處。 但這樣寫是為了避免SyntaxError錯誤。 ES2019可以省略catch周圍的括號:
try {// ... } catch {// .... } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的ES10 可以使用几个新特性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 龟毛是什么意思求解释
- 下一篇: touchstart与click同时触发