本文参考了 TC39 - proposals 中的 Finished Proposals 2019 年发布的部分。
Optional catch binding
该特性修改了 try…catch 的语法,catch 可以不带参数。
try {
throw new Error()
} catch {
console.log(1)
}
而之前的 try…catch 语法,catch 是需要带参数的,如:
try {
throw new Error()
} catch (error) {
console.log(1)
}
JSON superset
TC39 - Subsume JSON (a.k.a. JSON ⊂ ECMAScript) 提到这个特性的动机:
ECMAScript claims JSON as a subset in JSON.parse, but (as has been well-documented) that is not true because JSON strings can contain unescaped U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR characters while ECMAScript strings cannot.
These exceptions add unnecessary complexity to the specification and increase the cognitive burden on both implementers and users, allowing for the introduction of subtle bugs. Also, as a lesser but concrete corrolary problem, certain source concatenation and construction tasks currently require additional steps to process valid JSON into valid ECMAScript before embedding it.
简单的来说,就是在 ES10 之前,JSON 字符串中能够存在未经转移的 U+2028 字符和 U+2929 字符,而这个在 JavaScript 字符串并不能包含这两个未经转移的字符。ES10 中修复了这个问题。
Symbol.prototype.description
description
属性用于返回 Symbol 的可选参数 description:
Symbol('desc').toString(); // "Symbol(desc)"
Symbol('desc').description; // "desc"
Symbol('').description; // ""
Symbol().description; // undefined
Function.prototype.toString revision
该特性是 toString()
方法的修订,该方法返回一个字符串,该字符串为函数的源代码字符串。而在 ES10 之前,该字符串会将空格、换行、注释等全部清除掉,而 ES10 将会保留这些东西。
Object.fromEntries
新增的 Object.fromEntries
静态方法,接收一个可迭代的键值对列表,然后将它转换为对象:
obj = Object.fromEntries([['a', 0], ['b', 1]]); // { a: 0, b: 1 }
推荐阅读
String.prototype.trimStart,
trimStart()
方法将字符串开头的空格清除掉, trimLeft()
是该方法的别名。
String.prototype.trimEnd
trimEnd()
方法则是将字符串结尾的空格清除掉, trimRight()
是该方法的别名。
Array.prototype.flat
flat()
的作用为将原数组中所有的子数组元素以递归的方式向上提升多少层,如果不传参数,则数组中的子数组默认提升一层。
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]
推荐阅读:
Array.prototype.flatMap
flatMap
方法可以看成 map()
和 flat()
的结合体( flatMap()
默认提升的深度为 1),但是比起执行完 map()
之后再执行 flat()
要高效。
let arr1 = [1, 2, 3, 4];
arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]
arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]
// only one level is flattened
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]