這些很新的JS數(shù)組方法,還挺好用!
Array.prototype.at()
at() 方法允許通過索引訪問數(shù)組中的元素,支持負(fù)數(shù)索引來從數(shù)組末尾開始計數(shù)。
const arr = [10, 20, 30, 40];
console.log(arr.at(2)); // 輸出: 30
console.log(arr.at(-1)); // 輸出: 40
通常情況下,我們會使用[index]索引來獲取數(shù)組元素,但這種方式獲取正數(shù)元素還可以,如果想要獲取倒數(shù)元素,就麻煩一點(diǎn),這時就可以借助 at() 方法來實(shí)現(xiàn),只需指定一個負(fù)數(shù)即可。
瀏覽器支持情況:
Array.prototype.with()
with() 方法返回一個新數(shù)組,該數(shù)組是原數(shù)組的一個副本,但指定索引處的元素被替換為新的值。
const arr = [1, 2, 3, 4, 5];
const newArr = arr.with(2, 99); // 將索引2處的元素替換為99
console.log(newArr); // 輸出: [1, 2, 99, 4, 5]
console.log(arr); // 輸出: [1, 2, 3, 4, 5] (原數(shù)組不變)
當(dāng)需要更新數(shù)組中特定位置的元素但不想修改原數(shù)組時,可以使用 with() 方法。
瀏覽器支持情況:
Array.prototype.toSorted()
toSorted() 方法返回一個新數(shù)組,該數(shù)組是原數(shù)組經(jīng)過排序后的副本,不會修改原數(shù)組,它是 sort() 方法的復(fù)制版本。
const arr = [1, 5, 3, 2, 4];
const sortedArr = arr.toSorted((a, b) => a - b);
console.log(sortedArr); // 輸出: [1, 2, 3, 4, 5]
console.log(arr); // 輸出: [1, 5, 3, 2, 4] (原數(shù)組不變)
當(dāng)需要對數(shù)組進(jìn)行排序但不想修改原數(shù)組時,可以使用 toSorted() 方法。
瀏覽器支持情況:
Array.prototype.toReversed()
toReversed() 方法返回一個新數(shù)組,該數(shù)組是原數(shù)組反轉(zhuǎn)后的副本,不會修改原數(shù)組,它是 reverse() 方法對應(yīng)的復(fù)制版本。
const arr = [1, 2, 3, 4, 5];
const reversedArr = arr.toReversed();
console.log(reversedArr); // 輸出: [5, 4, 3, 2, 1]
console.log(arr); // 輸出: [1, 2, 3, 4, 5] (原數(shù)組不變)
當(dāng)需要反轉(zhuǎn)數(shù)組但不想修改原數(shù)組時,可以使用 toReversed() 方法。
瀏覽器支持情況:
Array.prototype.toSpliced()
toSpliced() 方法返回一個新數(shù)組,該數(shù)組是從原數(shù)組中刪除或替換某些元素后的新數(shù)組,不會修改原數(shù)組,它是 splice() 方法的復(fù)制版本。
const arr = [1, 2, 3, 4, 5];
const splicedArr = arr.toSpliced(2, 1, 99); // 從索引2開始刪除1個元素并插入99
console.log(splicedArr); // 輸出: [1, 2, 99, 4, 5]
console.log(arr); // 輸出: [1, 2, 3, 4, 5] (原數(shù)組不變)
當(dāng)需要從數(shù)組中刪除或替換某些元素但不想修改原數(shù)組時,可以使用 toSpliced() 方法。
瀏覽器支持情況:
Array.prototype.findLast()
findLast() 方法返回數(shù)組中滿足提供的測試函數(shù)的最后一個元素,類似 find() 的反向操作。如果沒有找到,則返回 undefined。
const arr = [5, 12, 8, 130, 44];
const found = arr.findLast(element => element > 10);
console.log(found); // 輸出: 44
當(dāng)需要在數(shù)組中查找符合條件的最后一個元素時,可以使用 findLast() 方法。
瀏覽器支持情況:
Array.prototype.findLastIndex()
findLastIndex() 方法返回數(shù)組中滿足提供的測試函數(shù)的最后一個元素的索引。如果沒有找到,則返回 -1。
const arr = [5, 12, 8, 130, 44];
const index = arr.findLastIndex(element => element > 10);
console.log(index); // 輸出: 4 (因?yàn)?4是最后一個大于10的元素)
當(dāng)需要在數(shù)組中查找符合條件的最后一個元素的索引時,可以使用 findLastIndex() 方法。
瀏覽器支持情況: