ES14中五個最具變革性的JavaScript特性
JavaScript在過去10年里取得了長足的進步,每年都有全新的功能升級。 讓我們來看看ES14(2023年)中引入的5個最重要的特性,看看你是否錯過了其中一些。
1. toSorted()
甜美的語法糖。
ES14的toSorted()方法使得排序數(shù)組并返回一個副本而不改變原數(shù)組變得更加容易。
以前我們這樣做:
const numbers = [3, 1, 4, 1, 5];
const sorted = [...numbers].sort((a, b) => a - b);
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(numbers); // [3, 1, 4, 1, 5]
現(xiàn)在我們可以這樣做?:
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.toSorted((a, b) => a - b);
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(numbers); // [3, 1, 4, 1, 5]
toSorted()接受一個回調(diào)函數(shù)來控制排序行為 - 升序或降序,按字母順序或數(shù)字順序。就像sort()一樣。
2. toReversed()
另一個新的數(shù)組方法,用于促進不可變性和函數(shù)式編程。
以前 — 使用reverse() ?:
const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.reverse();
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(numbers); // [5, 4, 3, 2, 1]
現(xiàn)在 — 使用toReversed() ?:
const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.toReversed();
console.log(reversed); // [5, 4, 3, 2, 1]
console.log(numbers); // [1, 2, 3, 4, 5]
我發(fā)現(xiàn)這些不可變方法非常棒,可以不斷地鏈?zhǔn)秸{(diào)用方法,而不用擔(dān)心原始變量:
const result = numbers.toReversed().toSorted((a, b) => a - b);
3. toSpliced()
函數(shù)式編程愛好者無疑會對所有這些新的數(shù)組方法感到高興。 這是.splice()的不可變版本:
const items = [1, 2, 3, 4, 5];
const newItems = items.toSpliced(2, 1, 6, 7);
console.log(newItems); // [1, 2, 6, 7, 4, 5]
console.log(items); // [1, 2, 3, 4, 5]
4. 從末尾開始查找數(shù)組
從第一項開始搜索并不總是理想的:
你可以很容易地看到,對我們的巨大列表從末尾而不是開始搜索會快得多。
有時你必須從末尾搜索才能讓你的程序工作。
比如我們想在一個數(shù)字列表中找到最后一個偶數(shù),find和findIndex會非常不準(zhǔn)確。 調(diào)用reverse()也不行,即使它會很慢:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const lastEven = numbers.reverse().find(n => n % 2 === 0);
console.log(lastEven); // 10(不正確)
所以在這種情況下,findLast()和findLastIndex()方法就派上用場了。
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const lastEven = numbers.findLast(n => n % 2 === 0);
console.log(lastEven); // 10(正確)
這段代碼更短、更易讀。最重要的是,它產(chǎn)生了正確的結(jié)果。
5. 數(shù)組的with()方法
with()是我們快速更改數(shù)組元素而不進行任何突變的方法。
以前的常規(guī)方式:
const arr = [1, 2, 3, 4, 5];
const newArr = [...arr];
newArr[2] = 6;
console.log(newArr); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
ES14現(xiàn)在讓我們這樣做:
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 6);
console.log(newArr); // [1, 2, 6, 4, 5]
console.log(arr); // [1, 2, 3, 4, 5]
最后的思考
還有其他特性,但ES14主要是關(guān)于更容易的函數(shù)式編程和內(nèi)置的不可變性。 隨著React的興起,我們看到聲明式JavaScript爆炸式地流行起來;很自然地,更多的這些特性會被烘焙到語言中,成為甜美的語法糖。