随着 JavaScript 语言的不断进化,ES10(也被称为 ECMAScript 2019)已经正式发布。除了修复了一些缺陷和错误之外,它还引入了一些具有实际意义的新特性。在本文中,我们将逐一介绍 ES10 中的所有新特性,并提供相关示例。
Array.prototype.flat()
在 ES10 中,Array 原型对象新增了一个 flat() 方法,它可以将嵌套的数组扁平化成一个新的数组。此方法还可以接受一个可选的参数,用于指定扁平化的深度。
const arr = [1, [2, [3, 4]]]; const flattened = arr.flat(); console.log(flattened); // [1, 2, [3, 4]] const deeplyFlattened = arr.flat(2); console.log(deeplyFlattened); // [1, 2, 3, 4]
Array.prototype.flatMap()
flatMap() 方法结合了两个常用的方法:map() 和 flat()。它首先调用 map() 方法,然后将输出数组调用 flat() 方法进行扁平化。
const arr = [1, 2, 3]; const mappedAndFlattened = arr.flatMap(x => [x * 2]); console.log(mappedAndFlattened); // [2, 4, 6]
String.prototype.trimStart() 和 String.prototype.trimEnd()
在 ES10 中,String 原型对象新增了两个方法:trimStart() 和 trimEnd(),它们分别用于删除字符串开头和结尾的空白字符。
const str = ' hello world '; const trimmedStart = str.trimStart(); console.log(trimmedStart); // 'hello world ' const trimmedEnd = str.trimEnd(); console.log(trimmedEnd); // ' hello world'
Object.fromEntries()
Object.fromEntries() 方法可以将键值对数组转换为对象。该方法是 Object.entries() 的反向操作。
const entries = [['name', 'John'], ['age', 30]];
const person = Object.fromEntries(entries);
console.log(person); // { name: 'John', age: 30 }try...catch 可以不使用 catch
在 ES10 中,try...catch 块可以不使用 catch 语句。在这种情况下,try 块如果发生任何异常,异常将会被传递到下一个 catch 或 finally 块。
try {
// do something that may generate an exception
} finally {
// this block will always execute, regardless of whether an exception was thrown or not
}Function.prototype.toString() 现在返回准确的函数源代码
在 ES10 中,Function 原型对象的 toString() 方法现在返回完整的函数源代码,包括注释和空格。
-- -------------------- ---- ------- -------- ------------- -- - -- ---- -------- ---- --------- ------ - - -- - ----------------------------------- -- --------- ------------- -- - -- -- ---- -------- ---- --------- -- ------ - - -- -- --
Symbol.prototype.description
在 ES10 中,Symbol.prototype.description 属性返回 Symbol 实例的可选描述。该描述被传递给 Symbol() 构造函数的第一个参数。
const mySymbol = Symbol('My optional symbol description');
console.log(mySymbol.description); // 'My optional symbol description'BigInt 数据类型
在 ES10 中,BigInt 数据类型被引入。它是一个用于存储任意精度整数的新的数据类型。
const bigInt = 2n ** 53n; console.log(bigInt); // 9007199254740992n console.log(typeof bigInt); // bigint
总结
ES10 提供了很多新特性,这些特性都有助于开发者更加轻松地编写更好的代码。我们了解了 ES10 中新增的 Array、String、Object、Function 和 Symbol 方法,同时也介绍了 try...catch 和 BigInt 数据类型。这些新特性都有深度和学习以及指导意义,可以更好地满足开发者在实际工作中的需求。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/64564192968c7c53b09792d7