App下載

ES2023有哪些新特性?

美少女上梁山 2024-03-07 16:55:05 瀏覽數(shù) (945)
反饋


從后向前查找數(shù)組元素

由Wenlu Wang提出的“從后向前查找數(shù)組元素”提案在Array和TypedArray原型上添加了findLast()和findLastIndex()方法。它們與find()和findIndex()方法具有相同的功能,但順序相反。這兩種方法很方便,讓我們避免創(chuàng)建臨時(shí)副本、突變和混淆的索引。

const isEven = (number) => number % 2 === 0;
const numbers = [1, 2, 3, 4];
?
// 從第一個(gè)到最后一個(gè)查找
console.log(numbers.find(isEven));
// 2
console.log(numbers.findIndex(isEven));
// 1
?
// 從最后一個(gè)到第一個(gè)查找
console.log(numbers.findLast(isEven));
// 4
console.log(numbers.findLastIndex(isEven));
// 3

Hashbang語法

Hashbang,也稱為shebang ,是可執(zhí)行腳本開頭的一系列字符,用于定義要運(yùn)行的程序的解釋器。當(dāng)Unix內(nèi)核的程序加載器執(zhí)行JavaScript程序時(shí),主機(jī)會(huì)剝離hashbang以生成有效的源代碼,然后將其傳遞給引擎。Bradley Farias提出的Hashbang語法提案規(guī)范了這個(gè)過程。

#!/usr/bin/env node
?
console.log('hi ??');

Symbol作為WeakMap鍵

在JavaScript中,對象和Symbol保證是唯一的,不能重新創(chuàng)建,這使它們都成為WeakMap鍵的理想候選者。先前的版本或規(guī)范只允許使用對象作為鍵,但幸運(yùn)的是,由Daniel Ehrenberg、Richard Button、Robin Ricard、Leo Balter、Rick Waldron和Caridy Pati?o提出的Symbol作為WeakMap鍵提案將未注冊的Symbol添加到允許的鍵列表中。

const weak = new WeakMap();
const key = Symbol("ref");
weak.set(key, "ECMAScript 2023");
?
console.log(weak.get(key));
// ECMAScript 2023

通過復(fù)制改變數(shù)組

Array.prototype 上的 reverse()、sort() 和 splice() 方法會(huì)就地突變數(shù)組。Ashley Claymore 和 Robin Ricard 提出的 Change Array by Copy proposal 添加了 toReversed()、toSorted() 和 toSpliced() 方法的副本,它們會(huì)返回一個(gè)新的數(shù)組。此提議還添加了一個(gè) with() 方法,該方法返回一個(gè)新數(shù)組,其中給定索引處的元素用給定值替換,以避免使用括號(hào)表示法進(jìn)行就地突變。

const original = [1, 2, 3, 4];
const reversed = original.toReversed();
?
console.log(original);
// [ 1, 2, 3, 4 ]
?
console.log(reversed);
// [ 4, 3, 2, 1 ]
const original = [1, 3, 2, 4];
const sorted = original.toSorted();
?
console.log(original);
// [ 1, 3, 2, 4 ]
?
console.log(sorted);
// [ 1, 2, 3, 4 ]
const original = [1, 4];
const spliced = original.toSpliced(1, 0, 2, 3);
?
console.log(original);
// [ 1, 4 ]
?
console.log(spliced);
// [ 1, 2, 3, 4 ]
const original = [1, 2, 2, 4];
const withThree = original.with(2, 3);
?
console.log(original);
// [ 1, 2, 2, 4 ]
?
console.log(withThree);
// [ 1, 2, 3, 4 ]


0 人點(diǎn)贊