ECMAScript 2023
JavaScript 版本号
早期的 ECMAScript 版本以数字命名:ES5 和 ES6。
从 2016 年开始,版本以年份命名:ES2016、2018、2020……
第 14 版,即 ECMAScript 2023,于 2023 年 6 月发布。
ES2023 中的新特性
- Array findLast()
- Array findLastIndex()
- Array toReversed()
- Array toSorted()
- Array toSpliced()
- Array with()
- #! (Shebang)
警告
这些功能相对较新。
较旧的浏览器可能需要替代代码(Polyfill)。
JavaScript Array findLast() 方法
ES2023 添加了 findLast()
方法,该方法将从数组的末尾开始,并返回满足条件的第一个元素的值。
实例
const temp = [27, 28, 30, 40, 42, 35, 30]; let high = temp.findLast(x => x > 40);
JavaScript Array findLastIndex() 方法
findLastIndex()
方法查找满足条件的最后一个元素的索引。
实例
const temp = [27, 28, 30, 40, 42, 35, 30]; let pos = temp.findLastIndex(x => x > 40);
JavaScript Array toReversed() 方法
ES2023 添加了 Array toReversed()
方法,作为一种在不改变原始数组的情况下反转数组的安全方式。
新的 toReversed()
方法与旧的 reverse()
方法的区别在于,新方法会创建一个新数组,保持原始数组不变,而旧方法会改变原始数组。
实例
const months = ["Jan", "Feb", "Mar", "Apr"]; const reversed = months.toReversed();
JavaScript Array toSorted() 方法
ES2023 添加了 Array toSorted()
方法,作为一种在不改变原始数组的情况下对数组进行排序的安全方式。
新的 toSorted()
方法与旧的 sort()
方法的区别在于,新方法会创建一个新数组,保持原始数组不变,而旧方法会改变原始数组。
实例
const months = ["Jan", "Feb", "Mar", "Apr"]; const sorted = months.toSorted();
JavaScript Array toSpliced() 方法
ES2023 添加了 Array toSpliced()
方法,作为一种在不改变原始数组的情况下拼接数组的安全方式。
新的 toSpliced()
方法与旧的 splice()
方法的区别在于,新方法会创建一个新数组,保持原始数组不变,而旧方法会改变原始数组。
实例
const months = ["Jan", "Feb", "Mar", "Apr"]; const spliced = months.toSpliced(0, 1);
JavaScript Array with() 方法
ES2023 添加了 Array with()
方法,作为一种在不改变原始数组的情况下更新数组元素的安全方式。
实例
const months = ["Januar", "Februar", "Mar", "April"]; const new = months.with(2, "March");
JavaScript Shebang (#!)
Shebang 是脚本开头的井号(#
)和感叹号(!
)的组合(#!
):
#!/usr/bin/env node
上面的示例告诉操作系统使用 node 程序来运行脚本。
现在,您可以使用 ./fileName.js
来运行 JavaScript 代码,而不是使用 node fileName.js
。
#!
也被称为 sharp-exclamation(尖感叹号)、hashbang(散列叹号)、pound-bang(井叹号)或 hash-pling(散列 pling)。