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)。