推荐答案
ES10(ES2019)中新增的主要特性包括:
Array.prototype.flat() 和 Array.prototype.flatMap()
flat()方法用于将嵌套的数组“拉平”,变成一维数组。可以指定拉平的层数。flatMap()方法首先对数组中的每个元素执行映射操作,然后将结果“拉平”一层。
Object.fromEntries()
- 将键值对列表(如
Map或Array)转换为对象。
- 将键值对列表(如
String.prototype.trimStart() 和 String.prototype.trimEnd()
trimStart()用于去除字符串开头的空白字符。trimEnd()用于去除字符串结尾的空白字符。
可选的 Catch 绑定
- 允许在
catch语句中省略绑定的错误变量。
- 允许在
Symbol.prototype.description
- 提供对
Symbol的描述的只读访问。
- 提供对
JSON 超集
- 确保 JSON 字符串可以包含未转义的换行符和分隔符。
Function.prototype.toString() 改进
- 返回函数源代码的精确表示,包括注释和空格。
BigInt
- 引入了一种新的原始数据类型
BigInt,用于表示任意精度的整数。
- 引入了一种新的原始数据类型
本题详细解读
1. Array.prototype.flat() 和 Array.prototype.flatMap()
flat()
flat()方法用于将多维数组“拉平”为一维数组。默认情况下,它只会拉平一层,但可以通过传递参数指定拉平的层数。const arr = [1, [2, [3, [4]]]]; console.log(arr.flat()); // [1, 2, [3, [4]]] console.log(arr.flat(2)); // [1, 2, 3, [4]] console.log(arr.flat(Infinity)); // [1, 2, 3, 4]
flatMap()
flatMap()方法结合了map()和flat()的功能。它首先对数组中的每个元素执行映射操作,然后将结果“拉平”一层。const arr = [1, 2, 3]; console.log(arr.flatMap(x => [x * 2])); // [2, 4, 6]
2. Object.fromEntries()
Object.fromEntries() 方法将键值对列表(如 Map 或 Array)转换为对象。
const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2 }3. String.prototype.trimStart() 和 String.prototype.trimEnd()
trimStart()
去除字符串开头的空白字符。const str = " hello "; console.log(str.trimStart()); // "hello "
trimEnd()
去除字符串结尾的空白字符。const str = " hello "; console.log(str.trimEnd()); // " hello"
4. 可选的 Catch 绑定
在 ES10 中,catch 语句可以省略绑定的错误变量。
try {
throw new Error('Oops');
} catch {
console.log('An error occurred');
}5. Symbol.prototype.description
Symbol.prototype.description 提供了对 Symbol 的描述的只读访问。
const sym = Symbol('foo');
console.log(sym.description); // "foo"6. JSON 超集
ES10 确保 JSON 字符串可以包含未转义的换行符和分隔符,使得 JSON 成为 ECMAScript 字符串的超集。
const json = '{"name": "John",\n"age": 30}';
console.log(JSON.parse(json)); // { name: 'John', age: 30 }7. Function.prototype.toString() 改进
Function.prototype.toString() 现在返回函数源代码的精确表示,包括注释和空格。
// www.javascriptcn.com code example
function foo() {
// This is a comment
return 'bar';
}
console.log(foo.toString());
// "function foo() {
// // This is a comment
// return 'bar';
// }"8. BigInt
BigInt 是一种新的原始数据类型,用于表示任意精度的整数。
const bigInt = 1234567890123456789012345678901234567890n; console.log(bigInt + 1n); // 1234567890123456789012345678901234567891n