沒人愿意使用這些數組方法,你會使用嗎?
前端開發中經常使用數組操作,除了常見的 map()、filter()、find() 和 push() 等方法外,JavaScript還提供了許多強大的數組方法。這篇文章將介紹7個實用但較少被關注的數組方法。
1. copyWithin(): 數組內部復制
這個方法可以在同一個數組內復制并替換元素,不會改變數組長度。
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3); // [4, 5, 3, 4, 5]
// 指定結束位置
const fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi'];
fruits.copyWithin(2, 0, 2); // ['apple', 'banana', 'apple', 'banana', 'kiwi']
2. at() 和 with(): 現代數組訪問方法
這兩個新方法提供了更優雅的數組元素訪問和修改方式:
const arr = ['a', 'b', 'c'];
// 使用負索引訪問最后一個元素
console.log(arr.at(-1)); // 'c'
// 不改變原數組的情況下修改元素
const newArr = arr.with(1, 'x'); // ['a', 'x', 'c']
console.log(arr); // ['a', 'b', 'c']
3. reduceRight(): 從右向左歸約
與 reduce() 類似,但從數組末尾開始處理:
// 構建嵌套對象
const keys = ['user', 'name', 'john'];
const nested = keys.reduceRight((value, key) => ({ [key]: value }), null);
// 結果: { user: { name: { john: null } } }
4. findLast(): 反向查找
ES13新增方法,從數組末尾開始查找元素:
const numbers = [2, 4, 6, 8, 9, 10, 12];
// 查找最后一個偶數
const lastEven = numbers.findLast(num => num % 2 === 0); // 12
5. 不可變數組操作方法
ES2023引入的新方法:toSorted()、toReversed()、toSpliced(),它們不會修改原數組:
const original = [3, 1, 4, 1, 5];
const sorted = original.toSorted(); // [1, 1, 3, 4, 5]
console.log(original); // [3, 1, 4, 1, 5]
6. lastIndexOf(): 查找最后匹配索引
查找指定元素最后出現的位置:
const text = ['hello', 'world', 'hello', 'javascript'];
console.log(text.lastIndexOf('hello')); // 2
console.log(text.lastIndexOf('hello', 1)); // 0
7. flatMap(): 映射并扁平化
結合了 map() 和 flat() 的功能,效率更高:
const sentences = ['Hello world', 'JavaScript is awesome'];
const words = sentences.flatMap(sentence => sentence.split(' '));
// ['Hello', 'world', 'JavaScript', 'is', 'awesome']
這些方法雖然使用頻率不高,但在特定場景下能夠顯著提升代碼質量和效率。建議在實際開發中根據具體需求選擇合適的數組方法。