[ES10] Javascript 開發者必須知道的新功能

Peter Chang
2 min readMay 14, 2019
[ES10] Javascript 開發者必須知道的新功能

ES10 在2019年 2月中就推出了,目前(May 2019)在新版的 Nodejs 和 Chrome 已經可享用 ,雖然沒有 ES6 來得偉大和有驚喜。

ES10 除了 flat() 和 flatmap() 值得注意之外,我個人很少會用到其他的新功能。只能期待 ES11 !

  1. [].flat() [].flatMap()
  2. Object.fromEntries
  3. “”.trimLeft()
  4. try{} catch{}
  5. Function to String
  6. Symbol Description

1.1) [].flat()

flat() 是用作打平 n 層或無限層的 Array,回傳一個新 Array:

const arr = [1, 2, [3, 4, [5, 6, [7, 8, 9]]]];console.log(arr.flat());                //[1,2,3,4,[5,6,[7,8,9]]]console.log(arr.flat().flat());         //[1,2,3,4,5,6,[7,8,9]]
console.log(arr.flat(2)); // same as above
console.log(arr.flat(Infinity)); //[1, 2, 3, 4, 5, 6]

1.2) [].flatMap()

flatMap()是串聯2個 Function: map().flat(1),注意是一層 flat(),回傳一個新 Array:

It maps each element using map() and flat() and turning into a new array. It’s identical to the map operation followed by a flat of depth 1.

const arr = [1, 2, 3, 4];console.log(arr.flatMap(x => [x, x + 10]))    // [1,11,2,12,3,13,4,14]
console.log(arr.map(x => [x, x + 10]).flat()) // same as above

2) Object.fromEntries

是轉換成對 [key, value] Array 成為一個 Object.

const entries = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(entries);console.log(obj);
// expected output: Object { foo: "bar", baz: 42 }

Object.fromEntries 剛好和 Object.entries 成對稱

const arr = [['a', 0], ['b', 1]]
const obj = Object.fromEntries(arr)
const arrt = Object.entries(obj)
// content of arrt is as same as arr

3) ''.trimLeft() / trimRight()

縮減空白字串,ES10 提供 trimLeft() trimRight() 2個方法:

const untrimmedString = "     Trim me 😢    ";console.log(untrimmedString.trimLeft());
// "Trim me 😢 ";
console.log(untrimmedString.trimRight());
// " Trim me 😢";

自己實作同樣功能雖然一行程式碼搞定,但這是一個很 nice 的功能,方便易用

4) optional catch()

可以省略 catch 回傳的表達參數 catch(err){} -> catch{}

try {
throw "Error we don't care about";
} catch { // param can be ignored
console.log('[ERROR] optional catch')
}

5) function.toString()

function.toString() 回傳確實的 Function 程式碼,包括空白字元和註解:

const fun1 = function(x) {
// fun2
}
const fun2 = (x) => {
// fun2
}
console.log(fun1.toString());
console.log(fun2.toString());
console.log([].map.toString()); // function map() { [native code] }

6) Symbol Description Accessor

在建構 symbol 時把 description 作第一個參數傳入,就可以通過 toString() 取得:

const symbolExample = Symbol("Symbol description");
console.log(symbolExample.toString());
// 'Symbol(Symbol description)'

我個人在工作上是沒有用過 Symbol

🎉 New JavaScript features in ES2019: ➡️ Array#{flat,flatMap} ➡️ Object.fromEntries ➡️ String#{trimStart,trimEnd} ➡️ Symbol#description ➡️ try { } catch {} // optional binding ➡️ JSON ⊂ ECMAScript ➡️ well-formed JSON.stringify ➡️ stable Array#sort ➡️ revised Function#toString

@mathias

Reference:

--

--