JavaScript數(shù)組的常用方法,然后列出常見的問題。
注意:數(shù)組方法可以分為以下幾類:變更方法(修改原數(shù)組)、訪問方法(不修改原數(shù)組)、迭代方法等。
一、數(shù)組常用方法
- 變更方法(修改原數(shù)組):
push():末尾添加一個或多個元素,返回新長度
pop():刪除最后一個元素,返回該元素
shift():刪除第一個元素,返回該元素
unshift():開頭添加一個或多個元素,返回新長度
splice():刪除、插入或替換元素,返回被刪除的元素組成的數(shù)組
sort():排序,默認按字符串Unicode碼點排序
reverse():反轉數(shù)組
- 訪問方法(不修改原數(shù)組):
concat():合并數(shù)組,返回新數(shù)組
slice(start, end):截取數(shù)組,返回新數(shù)組
join(separator):將數(shù)組連接成字符串
indexOf():返回指定元素第一次出現(xiàn)的索引
lastIndexOf():返回指定元素最后一次出現(xiàn)的索引
includes():判斷是否包含某元素
- 迭代方法(不修改原數(shù)組,但回調函數(shù)可以修改):
forEach():遍歷數(shù)組,無返回值
map():對每個元素調用回調,返回新數(shù)組
filter():過濾,返回滿足條件的元素組成的新數(shù)組
reduce():從左到右累加
reduceRight():從右到左累加
some():判斷是否至少有一個元素滿足條件
every():判斷是否所有元素都滿足條件
find():返回第一個滿足條件的元素
findIndex():返回第一個滿足條件的元素的索引
- ES6+ 新增方法:
Array.from():將類數(shù)組對象或可迭代對象轉換為數(shù)組
Array.of():將一組值轉換為數(shù)組
fill():填充數(shù)組
copyWithin():在數(shù)組內部復制元素
flat():數(shù)組扁平化
flatMap():先map再flat(1)
二、常見題
數(shù)組去重
數(shù)組扁平化(多維數(shù)組轉一維)
數(shù)組排序(包括自定義排序)
數(shù)組方法的實現(xiàn)(如實現(xiàn)map、filter、reduce等)
數(shù)組的深拷貝
數(shù)組和類數(shù)組的區(qū)別及轉換
數(shù)組的遍歷方法比較(for、forEach、for...in、for...of)
使用reduce實現(xiàn)復雜功能(如實現(xiàn)map、filter等)
數(shù)組的常見操作(合并、截取、反轉等)
數(shù)組的迭代方法的應用(如some、every、find等)
三、常被問的題(示例)
- 數(shù)組去重的多種實現(xiàn)方式
使用Set
使用filter+indexOf
使用reduce
使用對象鍵值對
- 數(shù)組扁平化(多維數(shù)組轉一維)
遞歸
使用flat方法
使用reduce遞歸
使用擴展運算符
手寫數(shù)組方法(如map、filter、reduce等)
數(shù)組排序(如按對象的某個屬性排序)
數(shù)組的深拷貝(考慮多層嵌套)
類數(shù)組轉數(shù)組(arguments、NodeList等)
使用數(shù)組方法解決復雜問題(如求交集、并集、差集)
數(shù)組遍歷的性能比較
數(shù)組的哪些方法會改變原數(shù)組,哪些不會
數(shù)組的空位處理(如[1,,3])
下面我們詳細展開一些常見題的解答:
JavaScript 數(shù)組方法大全及高頻題解析
一、數(shù)組核心方法分類
| 類型 | 方法 | 特點 |
|---|---|---|
| 增刪改 |
push()/pop()/shift()/unshift()/splice()
|
修改原數(shù)組 |
| 轉換 |
join()/toString()/Array.from()/Array.of()
|
生成新格式 |
| 截取 |
slice()/concat()
|
返回新數(shù)組 |
| 查找 |
indexOf()/lastIndexOf()/find()/findIndex()/includes()
|
返回位置或元素 |
| 遍歷 |
forEach()/map()/filter()/reduce()/some()/every()
|
迭代處理 |
| 排序 |
sort()/reverse()
|
修改原數(shù)組 |
| ES6+ |
flat()/flatMap()/fill()/copyWithin()
|
新增功能 |
二、高頻題及解析
1. map() vs forEach() 區(qū)別?
const arr = [1, 2, 3];
// map:返回新數(shù)組
const mapped = arr.map(x => x * 2); // [2, 4, 6]
// forEach:無返回值
arr.forEach(x => console.log(x)); // 1, 2, 3
-
map():返回新數(shù)組,適合數(shù)據(jù)轉換 -
forEach():僅遍歷,無返回值
2. 實現(xiàn)數(shù)組去重(3種方法)
// 方法1:Set(ES6最簡單)
const unique1 = [...new Set([1,2,2,3])]; // [1,2,3]
// 方法2:filter + indexOf
const unique2 = [1,2,2,3].filter(
(item, idx, arr) => arr.indexOf(item) === idx
);
// 方法3:reduce
const unique3 = [1,2,2,3].reduce(
(acc, cur) => acc.includes(cur) ? acc : [...acc, cur], []
);
3. reduce() 高級用法
// 1. 數(shù)組求和
[1,2,3].reduce((sum, n) => sum + n, 0); // 6
// 2. 二維數(shù)組轉對象
const arr = [['name','Alice'], ['age',30]];
arr.reduce((obj, [key, val]) => ({...obj, [key]: val}), {});
// 3. 實現(xiàn)數(shù)組扁平化
const flatten = arr => arr.reduce(
(flat, next) => flat.concat(Array.isArray(next) ? flatten(next) : next), []
);
4. 數(shù)組排序陷阱
// 數(shù)字排序錯誤做法
[10, 5, 100].sort(); // [10, 100, 5](按字符串Unicode排序)
// 正確做法
[10, 5, 100].sort((a, b) => a - b); // [5, 10, 100]
// 對象數(shù)組排序
const users = [
{name: 'Alice', age: 30},
{name: 'Bob', age: 25}
];
users.sort((a, b) => a.age - b.age); // 按年齡升序
5. 數(shù)組方法實現(xiàn)原理(手寫)
// 手寫 map()
Array.prototype.myMap = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
// 手寫 filter()
Array.prototype.myFilter = function(callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
6. 數(shù)組空位處理
const arr = [1, , 3]; // 空位
// ES5 方法跳過空位
arr.forEach(x => console.log(x)); // 1, 3
// ES6 方法視空位為 undefined
Array.from(arr); // [1, undefined, 3]
[...arr]; // [1, undefined, 3]
7. 數(shù)組扁平化(多維轉一維)
const arr = [1, [2, [3, [4]]]];
// 方法1:flat(Infinity)
arr.flat(Infinity); // [1,2,3,4]
// 方法2:reduce + 遞歸
function flatten(arr) {
return arr.reduce(
(acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []
);
}
// 方法3:toString(僅數(shù)字數(shù)組)
arr.toString().split(',').map(Number);
8. 類數(shù)組轉真數(shù)組
// DOM元素列表
const nodeList = document.querySelectorAll('div');
// 轉換方法
const arr1 = Array.from(nodeList);
const arr2 = [...nodeList];
const arr3 = [].slice.call(nodeList);
9. 數(shù)組性能對比題
// 創(chuàng)建10萬元素數(shù)組
const largeArray = Array(100000).fill(0);
// 測試 for vs forEach vs for...of
console.time('for');
for (let i = 0; i < largeArray.length; i++) {} // 最快
console.timeEnd('for');
console.time('forEach');
largeArray.forEach(() => {}); // 次之
console.timeEnd('forEach');
console.time('for...of');
for (const item of largeArray) {} // 最慢
console.timeEnd('for...of');
10. 數(shù)組方法鏈式調用
const data = [
{id: 1, value: 10, active: true},
{id: 2, value: 20, active: false},
{id: 3, value: 30, active: true}
];
// 鏈式處理:激活狀態(tài)對象 → 值翻倍 → 求和
const result = data
.filter(item => item.active)
.map(item => item.value * 2)
.reduce((sum, val) => sum + val, 0); // 80
三、數(shù)組核心考點總結
-
方法特性:
- 哪些方法修改原數(shù)組(
sort,splice等) - 哪些返回新數(shù)組(
map,filter等)
- 哪些方法修改原數(shù)組(
-
性能優(yōu)化:
- 大數(shù)據(jù)集避免鏈式調用(中間數(shù)組浪費內存)
- 遍歷優(yōu)先用
for循環(huán)
-
ES6+ 特性:
-
Array.from()處理類數(shù)組 -
flat()多維數(shù)組扁平化 - 空位處理差異
-
-
函數(shù)式編程:
-
map/filter/reduce組合應用 - 避免副作用(純函數(shù))
-
-
手寫實現(xiàn):
- 常考
map、filter、reduce實現(xiàn) - 理解迭代器協(xié)議
- 常考
建議:遇到數(shù)組問題先明確需求 - 需要返回新數(shù)組還是修改原數(shù)組?數(shù)據(jù)規(guī)模如何?是否需要考慮兼容性?掌握核心方法的特性組合使用能解決90%的數(shù)組相關問題。