ES2019 简要概述
ES2019 为我们带来了一些新特性。本文将概述其中的主要特性(以及需要注意的问题),并提供其他次要更新的链接。
这些功能在 v8、v7.3 和 Chrome 73 中均可使用。在其他版本中使用这些功能时,请务必检查其是否受支持。
Array.prototype.flat()
默认情况下,它会将一个层展平。
[1, 2, [3, 4]].flat();
// [1, 2, 3, 4]
[1, 2, [3, [4, 5]]].flat();
// [1, 2, 3, [4, 5]]
您可以调整层数以使其扁平化。
[1, 2, [3, [4, 5]]].flat(2);
// [1, 2, 3, 4, 5]
陷阱
undefined如果嵌套,则缺少某个项目将导致错误。
[1, 2, [3, [4,[, 6]]]].flat(2);
// [1, 2, 3, 4, [undefined, 6]]
如果缺失的项不是嵌套项,则会将其删除。
[1, 2, [3, [4,[, 6]]]].flat(3);
// [1, 2, 3, 4, 6]
Array.prototype.flatMap()
如果回调函数返回的是一个数组,则该值将被扁平化一级。
[1, 2, 3, 4].flatMap((n) => [n]);
// [1, 2, 3, 4]
[1, 2, 3, 4, 5].flatMap((n) => [[n]]);
// [[1], [2], [3], [4], [5]]
否则,它将按原样返回该值。
[1, 2, 3, 4].flatMap((n) => n);
// [1, 2, 3, 4]
[[1], 2, [3], 4].flatMap((n) => n);
// [1, 2, 3, 4]
如果您需要筛选和映射值,它将非常有用。
[1, 2, 3, 4, 5].flatMap(
(a) => a % 2 ? a + " is odd" : []
);
// ["1 is odd", "3 is odd", "5 is odd”]
陷阱
如果提供第二个参数,则变为this
var stuff = 'stuff';
[1, 2, 3, 4, 5].flatMap(
function(n) {
return `${this.stuff} ${n}`;
},
{ stuff: 'thing' }
);
// ["thing 1", "thing 2", "thing 3", "thing 4", "thing 5"]
Object.fromEntries()
[key, value]从任何包含元组的可迭代对象(Map、Array 或自定义可迭代对象)创建对象
Object.fromEntries([['one', 1], ['two', 2], ['three', 3]]);
// { one: 1, three: 3, two: 2 }
Object.fromEntries(new Map([['one', 1]]));
// { one: 1 }
Object.fromEntries(Object.entries({ one: 1 }));
// { one: 1 }
陷阱
如果与 Set 一起使用,将会抛出错误。
Object.fromEntries(new Set(["1"]));
// TypeError: Iterator value one is not an entry object
String.prototype.{trimStart, trimEnd}
' hello world '.trimStart();
// “hello world “
' hello world '.trimEnd();
// “ hello world”
' hello world '.trimStart().trimEnd();
// “hello world”
陷阱
trimLeft 和 trimRight 现在分别是 trimStart 和 trimEnd 的别名。
可选的卡扣式绑定
Catch 不再需要错误参数,即catch(error) {...}
let catchResult = 'uncaught';
try {
throw new Error();
} catch {
catchResult = 'caught';
}
console.log(catchResult);
// “caught”
陷阱
catch()仍然不允许;如果()存在,则必须带有参数。
try {
throw new Error();
} catch() {
catchResult = 'caught';
}
// SyntaxError: Unexpected token !
ES2019 的其他变更
其余的改动要么是内部改动,要么使用场景不多,但了解一下仍然很有用……
Symbol.prototype.description
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/description
稳定数组.prototype.sort()
https://mathiasbynens.be/demo/sort-stability
格式良好的 JSON.stringify()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Well-formed_JSON.stringify()
JSON 超集
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#JavaScript_and_JSON_differences(参见“任何 JSON 文本都是有效的 JavaScript 表达式”)
修订/标准化的 Function.prototype.toString()
https://tc39.es/Function-prototype-toString-revision/#sec-introduction