ECMA 2023(ES14) 新特性
ECMAScript 2023 主要包含內(nèi)容
ECMAScript 2023 于 2023 年 6 月 27 日獲得 ECMA International 的批準(zhǔn)。
ECMAScript 是標(biāo)準(zhǔn)化的 JavaScript 語言,于 1997 年發(fā)布了第一版,現(xiàn)已發(fā)展成為世界上使用最廣泛的通用編程語言之一。
本 Ecma 標(biāo)準(zhǔn)定義了 ECMAScript 2023 Language,是 ECMAScript 語言規(guī)范的第 14 版。
從后向前遍歷數(shù)組
它們的用法和find()、findIndex()類似,唯一不同的是它們是 從后向前遍歷數(shù)組,這兩個方法適用于數(shù)組和類數(shù)組。
findLast()會返回第一個查找到的元素,如果沒有找到,就會返回undefined;findLastIndex()會返回第一個查找到的元素的索引。如果沒有找到,就會返回 -1;
示例:
const array = [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }];
array.find((n) => n.value % 2 === 1); // { value: 1 }
array.findIndex((n) => n.value % 2 === 1); // 0
// ======== proposal 之前 ===========
// find
[...array].reverse().find((n) => n.value % 2 === 1); // { value: 3 }
// findIndex
array.length - 1 - [...array].reverse().findIndex((n) => n.value % 2 === 1); // 2
array.length - 1 - [...array].reverse().findIndex((n) => n.value === 42); // should be -1, but 4
// ======== proposal 之后 ===========
// find
array.findLast((n) => n.value % 2 === 1); // { value: 3 }
// findIndex
array.findLastIndex((n) => n.value % 2 === 1); // 2
array.findLastIndex((n) => n.value === 42); // -1
Hashbang
此提案是為了匹配某些允許 Shebangs/Hashbang 的 CLI JS 主機中的實際用法。
目前,此類主機會剝離 hashbang,以便在傳遞給 JS 引擎之前生成有效的 JS 源文本。這會將剝離轉(zhuǎn)移到發(fā)動機上,它確實統(tǒng)一并標(biāo)準(zhǔn)化了剝離的方式。
示例:
#!/usr/bin/env node
// 在腳本目標(biāo)中
"use strict";
console.log(1);
#!/usr/bin/env node
// 在模塊目標(biāo)中
export {};
console.log(1);
使用 Symbol 作為 WeakMap 鍵
目前,WeakMap 僅允許使用對象作為鍵,這是 WeakMap 的一個限制。新功能擴展了 WeakMap API,允許使用唯一的 Symbol 作為鍵
示例:
const weak = new WeakMap();
// 使用符號使它成為一個更具意義的 key
const key = Symbol("my ref");
const someObject = {
/* data data data */
};
weak.set(key, someObject);
使用復(fù)制的方法更改數(shù)組內(nèi)容
該提案在 Array.prototype 和 TypedArray.prototype 上提供了額外的方法,通過返回包含更改的新副本來啟用對數(shù)組的更改。
該提案向 Array.prototype 引入了以下函數(shù)屬性:
Array.prototype.toReversed() -> ArrayArray.prototype.toSorted(compareFn) -> ArrayArray.prototype.toSpliced(start, deleteCount, ...items) -> ArrayArray.prototype.with(index, value) -> Array
所有這些方法都保持目標(biāo)數(shù)組不變,并返回執(zhí)行更改的副本。
toReversed 、 toSorted 和 with 也將被添加到 TypedArrays 中:
TypedArray.prototype.toReversed() -> TypedArrayTypedArray.prototype.toSorted(compareFn) -> TypedArrayTypedArray.prototype.with(index, value) -> TypedArray
示例:
const sequence = [1, 2, 3];
sequence.toReversed(); // => [3, 2, 1]
sequence; // => [1, 2, 3]
const outOfOrder = new Uint8Array([3, 1, 2]);
outOfOrder.toSorted(); // => Uint8Array [1, 2, 3]
outOfOrder; // => Uint8Array [3, 1, 2]
const correctionNeeded = [1, 1, 3];
correctionNeeded.with(1, 2); // => [1, 2, 3]
correctionNeeded; // => [1, 1, 3]
參考內(nèi)容
本文來自博客園,作者:_zhiqiu,轉(zhuǎn)載請注明原文鏈接:http://www.rzrgm.cn/guojikun/p/18206186

浙公網(wǎng)安備 33010602011771號