喜大普奔,es2019登場

 

點擊上方“秋風的筆記”關注我們

就在剛4個小時前,TC39將以下特性加入到了 ES2019 中。讓我們來看看這些新的特性給我們帶來了什麼樣的改變。

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

JSON ⊂ ECMAScript (JSON superset)

行分隔符(U + 2028)和段分隔符(U + 2029)符號現在允許在字符串文字中,與JSON匹配。 以前,這些符號在字符串文字中被視爲行終止符,因此使用它們會導致SyntaxError異常。

well-formed JSON.stringify

更加友好的 JSON.stringify (修復了對於一些超出範圍的 unicode 展示錯誤的問題。)

如果輸入 Unicode 格式但是超出範圍的字符,在原先JSON.stringify返回格式錯誤的Unicode字符串:

JSON.stringify('\uD800');
// → '"�"'

現在實現了一個改變JSON.stringify的第3階段提案,因此它爲其輸出轉義序列,使其成爲有效Unicode(並以UTF-8表示):

JSON.stringify('\uD800');
// → '"\ud800"'

stable Array#sort

在以前,sort 函數中,10個以上元素的數組 V8 使用不穩定的QuickSort(快排。現在,使用穩定的TimSort算法。)

TimSort算法: https://en.wikipedia.org/wiki/Timsort

revised Function#toString

Function.prototype.toString()現在返回精確字符,包括空格和註釋。原先和現在的比較:

// Note the comment between the `function` keyword
// and the function name, as well as the space following
// the function name.
function /* a comment */ foo () {}
// Previously:
foo.toString();
// → 'function foo() {}'
//             ^ no comment
//                ^ no space
// Now:
foo.toString();
// → 'function /* comment */ foo () {}'

Array #{flat, flatMap}

數組降維,遞歸地將數組展平到指定的深度,默認爲1。

// Flatten one level:
const array = [1, [2, [3]]];
array.flat();
// → [1, 2, [3]]
// Flatten recursively until the array contains no more nested arrays:
array.flat(Infinity);
// → [1, 2, 3]
[2, 3, 4].flatMap((x) => [x, x * 2]);
// → [2, 4, 3, 6, 4, 8]

Object.fromEntries

Object.fromEntries(Object.entries(object))≈ 對象

它類似於Lodash的_.fromPairs。

String#{trimStart,trimEnd}

前後的空白符可以指定一邊去除。

const string = '  hello world  ';
string.trimStart();
// → 'hello world  '
string.trimEnd();
// → '  hello world'
string.trim();
// → 'hello world'

Symbol.prototype.description

通過工廠函數Symbol()創建符號時,您可以選擇通過參數提供字符串作爲描述:

const sym = Symbol('The description');

以前,訪問描述的唯一方法是將符號轉換爲字符串:

assert.equal(String(sym), 'Symbol(The description)');

現在引入了getter Symbol.prototype.description以直接訪問描述:

assert.equal(sym.description, 'The description');

try {} catch {}

現在try {} catch {} 有了更加簡便的方法,變成了可選型。

在以前

try {} catch (e) {}

現在

更多提案:

https://github.com/tc39/proposals/blob/master/finished-proposals.md

長按二維碼,可以關注我喲

萬水千山總是情,點個小贊行不行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章