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