ES10 新增了几个 JavaScript 内置方法
在 JavaScript 中,内置方法是非常重要和必要的。ES10 版本中新增了一些内置方法,本文将对它们进行详细介绍。
- trimStart 和 trimEnd
trimStart 和 trimEnd 方法可以在字符串的开始和结束处删除空格。
以往需要使用正则表达式或者其他方法来实现,但现在只需要使用这两个方法即可。
示例代码:
const str = " hello world "; console.log(str.trimStart()); console.log(str.trimEnd());
输出结果:
"hello world " " hello world"
- flat 和 flatMap
flat 方法可以将多维数组变成一维数组,而 flatMap 方法则可以对每个元素进行操作。
示例代码:
const arr = [ [1, 2], [3, 4], [5, 6] ]; console.log(arr.flat()); console.log(arr.flatMap(x => x * 2));
输出结果:
[1, 2, 3, 4, 5, 6] [2, 4, 6, 8, 10, 12]
- fromEntries
fromEntries 方法可以将键值对数组转换为对象。
示例代码:
const arr = [ ['name', 'Alice'], ['age', 18], ['gender', 'female'] ]; console.log(Object.fromEntries(arr));
输出结果:
{ name: "Alice", age: 18, gender: "female" }
- Optional Catch Binding
Optional Catch Binding 可选绑定可以让 catch 块中的异常不一定需要绑定到变量上。
示例代码:
try { somethingThatMayThrowAnError(); } catch { console.log("Error occurred, but we don't care what it is."); }
输出结果:
Error occurred, but we don't care what it is.
结语
ES10 新增了这几个内置方法,可以为我们的编程生涯带来更多的方便和效率。它们在实际开发中具有重要的学习和指导意义。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67b6f4fe306f20b3a6371bc6