JavaScript 35个数组方法完整参数返回值表
前言
本文可以看做是之前文章的升级版
JavaScript 数组 array 相关知识整理
使用了Deepseek帮助总结
JavaScript 35个数组方法完整参数返回值表
牢记五字真言 “增-删-改-查-判”
| 分类 | 方法 | 参数 | 返回值 |
| 增 | concat() | ...arrays: any[] | 新数组(合并后) |
| push() | ...elements: any[] | 新数组长度 | |
| unshift() | ...elements: any[] | 新数组长度 | |
| 删 | pop() | 无参数 | 被删除的元素 |
| shift() | 无参数 | 被删除的元素 | |
| slice() | start?: number, end?: number | 截取原数组的一部分,返回新数组 | |
| splice() | start: number, deleteCount?: number, ...items?: any[] | 添加/删除,返回被删除的元素组成的数组 | |
| 改(数组) | from() | arrayLike: any, mapFn?: (element, index) => any | 将类数组或可迭代对象转为数组 |
| of() | ...elements: any[] | 将一组参数转为数组 | |
| 改元素 | copyWithin() | target: number, start: number, end?: number | 复制部分数组到该数组中其他位置,不改变原数组长度,返回修改后的数组 |
| fill() | value: any, start?: number, end?: number | 数组填充,返回修改后的数组 | |
| 扁平 | flat() | depth?: number | 新数组(扁平后) |
| 归并 | reduce() | callback: (accumulator, current, index, array) => any, initialValue?: any | 累加结果 |
| reduceRight() | callback: (accumulator, current, index, array) => any, initialValue?: any | 累加结果 | |
| 排序 | sort() | compareFunction?: (a, b) => number | 排序后的原数组(默认升序) |
| reverse() | 无参数 | 反转后的原数组 | |
| 转字符串 | join() | separator?: string | string |
| toString() | 无参数 | string | |
| toLocaleString() | 无参数 | string | |
| 查:怎么查(遍历) | forEach() | callback: (element, index, array) => void | undefined |
| 映射 | map() | callback: (element, index, array) => any | 新数组 |
| flatMap() | callback: (element, index, array) => any | 新数组(扁平后) | |
| 迭代 | keys() | 无参数 | Array Iterator |
| values() | 无参数 | Array Iterator | |
| entries() | 无参数 | Array Iterator | |
| 过滤 | filter() | callback: (element, index, array) => boolean | 新数组(过滤后) |
| 查什么(位置) | indexOf() | searchElement: any, fromIndex?: number | 索引位置或-1 |
| lastIndexOf() | searchElement: any, fromIndex?: number | 索引位置或-1 | |
| 查元素 | at() | index: number (支持负数) | 对应元素或undefined |
| find() | callback: (element, index, array) => boolean | 找到的元素或undefined | |
| findIndex() | callback: (element, index, array) => boolean | 索引位置或-1 | |
| 判 | isArray() | value: any | boolean |
| includes() | searchElement: any, fromIndex?: number | boolean | |
| some() | callback: (element, index, array) => boolean | boolean | |
| every() | callback: (element, index, array) => boolean | boolean |
参数类型速记表
| 参数类型 | 说明 | 常用方法 |
|---|---|---|
callback函数 | (element, index, array) => any | map, filter, forEach, find, some, every, reduce |
起始位置 | start?: number | slice, splice, indexOf, includes, copyWithin, fill |
搜索元素 | searchElement: any | indexOf, lastIndexOf, includes |
分隔符 | separator?: string | join |
深度 | depth?: number | flat |
比较函数 | compareFunction?: (a, b) => number | sort |
初始值 | initialValue?: any | reduce, reduceRight |
返回值类型分类表
| 返回值类型 | 方法 | 特点 |
|---|---|---|
| 新数组 | map, filter, slice, concat, flat, flatMap, from, of | 不改变原数组 |
| 原数组 | push, pop, shift, unshift, splice, sort, reverse, copyWithin, fill | 改变原数组 |
| boolean | includes, some, every, isArray | 判断结果 |
| 索引/元素 | indexOf, lastIndexOf, findIndex, find, at | 查找结果 |
| 数值 | push, unshift | 返回长度 |
| 字符串 | join, toString, toLocaleString | 字符串结果 |
| 迭代器 | keys, values, entries | 可迭代对象 |
| 累加结果 | reduce, reduceRight | 归并计算结果 |
| undefined | forEach | 无返回值 |
重要参数模式
// 1. 回调函数三件套 (元素, 索引, 数组)
arr.map((element, index, array) => { })// 2. 起始位置 + 结束位置
arr.slice(start, end)
arr.fill(value, start, end)// 3. 目标位置 + 源位置
arr.copyWithin(target, start, end)
flatMap()方法使用示例详解
基本语法
array.flatMap(callback(currentValue, index, array), thisArg)
-
参数:映射函数
(element, index, array) => newValue -
返回值:新数组(先映射后扁平化一级)
1. 基础使用示例
示例1:数组元素展开
const arr = [1, 2, 3];// 每个元素变成包含自身和加1的数组 const result = arr.flatMap(x => [x, x + 1]); console.log(result); // [1, 2, 2, 3, 3, 4]// 对比 map() 的效果 const mapResult = arr.map(x => [x, x + 1]); console.log(mapResult); // [[1, 2], [2, 3], [3, 4]]
示例2:过滤并展开
const numbers = [1, 2, 3, 4, 5];// 只处理偶数,并展开为多个元素
const result = numbers.flatMap(x => {return x % 2 === 0 ? [x, x * 2] : [];
});
console.log(result); // [2, 4, 4, 8]
2. 实际应用场景
场景1:句子分词
const sentences = ["Hello world", "JavaScript is awesome", "Web development"];// 将句子分割成单词并扁平化
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words);
// ["Hello", "world", "JavaScript", "is", "awesome", "Web", "development"]// 对比:使用 map() + flat() 的等价写法
const words2 = sentences.map(sentence => sentence.split(' ')).flat();
console.log(words2); // 相同结果
场景2:数据清洗和转换
const data = [{ name: "Alice", tags: ["js", "web"] },{ name: "Bob", tags: ["python", "data"] },{ name: "Charlie", tags: [] }
];// 提取所有标签并扁平化
const allTags = data.flatMap(person => person.tags);
console.log(allTags); // ["js", "web", "python", "data"]// 自动过滤空数组
const emptyFiltered = data.flatMap(person => person.tags || []);
console.log(emptyFiltered); // ["js", "web", "python", "data"]
场景3:矩阵操作
const matrix = [[1, 2],[3, 4],[5, 6] ];// 矩阵转置的思路(简化版) const flattened = matrix.flatMap(row => row); console.log(flattened); // [1, 2, 3, 4, 5, 6]// 每个元素乘以2并展开 const doubled = matrix.flatMap(row => row.map(x => x * 2)); console.log(doubled); // [2, 4, 6, 8, 10, 12]
3. 高级应用示例
示例1:嵌套数组处理
const nestedArrays = [[1], [2, 3], [4, 5, 6]];// 展开并给每个元素添加索引信息
const result = nestedArrays.flatMap((subArray, index) => subArray.map(value => ({ value, originalIndex: index }))
);
console.log(result);
// [
// {value: 1, originalIndex: 0},
// {value: 2, originalIndex: 1},
// {value: 3, originalIndex: 1},
// {value: 4, originalIndex: 2},
// {value: 5, originalIndex: 2},
// {value: 6, originalIndex: 2}
// ]
示例2:数据分组展开
const students = [{ name: "Alice", scores: [85, 90] },{ name: "Bob", scores: [78, 82] },{ name: "Charlie", scores: [95] }
];// 将每个学生和分数配对展开
const scoreDetails = students.flatMap(student =>student.scores.map(score => ({student: student.name,score: score}))
);
console.log(scoreDetails);
// [
// {student: "Alice", score: 85},
// {student: "Alice", score: 90},
// {student: "Bob", score: 78},
// {student: "Bob", score: 82},
// {student: "Charlie", score: 95}
// ]
示例3:条件性展开
const products = [{ name: "Laptop", categories: ["electronics", "computers"] },{ name: "Book", categories: ["education"] },{ name: "Phone", categories: ["electronics", "communication"] }
];// 只展开电子类产品的分类
const electronicCategories = products.flatMap(product =>product.categories.includes("electronics") ? product.categories : []
);
console.log(electronicCategories);
// ["electronics", "computers", "electronics", "communication"]
4. 与相关方法对比
flatMap() vs map() + flat()
const arr = [1, 2, 3];// 这三种写法等价 const result1 = arr.flatMap(x => [x, x * 2]); const result2 = arr.map(x => [x, x * 2]).flat(); const result3 = [].concat(...arr.map(x => [x, x * 2]));console.log(result1); // [1, 2, 2, 4, 3, 6] console.log(result2); // [1, 2, 2, 4, 3, 6] console.log(result3); // [1, 2, 2, 4, 3, 6]
性能考虑
// flatMap() 通常比 map().flat() 性能更好
// 因为只需要遍历一次数组const largeArray = Array.from({ length: 10000 }, (_, i) => i);// 使用 flatMap(推荐)
console.time('flatMap');
const result1 = largeArray.flatMap(x => [x, x + 1]);
console.timeEnd('flatMap');// 使用 map + flat
console.time('mapFlat');
const result2 = largeArray.map(x => [x, x + 1]).flat();
console.timeEnd('mapFlat');
5. 注意事项
注意1:只扁平化一级
const arr = [1, 2, 3];// flatMap 只扁平化一级 const result = arr.flatMap(x => [[x, x * 2]]); console.log(result); // [[1, 2], [2, 4], [3, 6]] - 仍然是嵌套数组// 需要多级扁平化时 const deepResult = arr.flatMap(x => [[x, x * 2]]).flat(); console.log(deepResult); // [1, 2, 2, 4, 3, 6]
注意2:返回非数组值
const arr = [1, 2, 3];// 如果回调函数返回非数组值,会自动包装成数组 const result = arr.flatMap(x => x * 2); console.log(result); // [2, 4, 6] - 相当于 map(x => x * 2)// 等价于 const result2 = arr.flatMap(x => [x * 2]); console.log(result2); // [2, 4, 6]
总结
flatMap() 的核心优势:
-
一次性操作:映射 + 扁平化一级
-
代码简洁:避免
map().flat()的链式调用 -
自动过滤:返回空数组时自动过滤掉
-
性能优化:通常比分开操作性能更好
使用场景:数据转换、文本处理、矩阵操作、条件性展开等需要同时进行映射和扁平化的场景。
