当前位置: 首页 > news >正文

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?: stringstring
toString()无参数string
toLocaleString()无参数string
:怎么查(遍历)forEach()callback: (element, index, array) => voidundefined
映射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: anyboolean
includes()searchElement: any, fromIndex?: numberboolean
some()callback: (element, index, array) => booleanboolean
every()callback: (element, index, array) => booleanboolean

参数类型速记表

参数类型说明常用方法
callback函数(element, index, array) => anymapfilterforEachfindsomeeveryreduce
起始位置start?: numberslicespliceindexOfincludescopyWithinfill
搜索元素searchElement: anyindexOflastIndexOfincludes
分隔符separator?: stringjoin
深度depth?: numberflat
比较函数compareFunction?: (a, b) => numbersort
初始值initialValue?: anyreducereduceRight

返回值类型分类表

返回值类型方法特点
新数组mapfiltersliceconcatflatflatMapfromof不改变原数组
原数组pushpopshiftunshiftsplicesortreversecopyWithinfill改变原数组
booleanincludessomeeveryisArray判断结果
索引/元素indexOflastIndexOffindIndexfindat查找结果
数值pushunshift返回长度
字符串jointoStringtoLocaleString字符串结果
迭代器keysvaluesentries可迭代对象
累加结果reducereduceRight归并计算结果
undefinedforEach无返回值

重要参数模式

// 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() 的链式调用

  • 自动过滤:返回空数组时自动过滤掉

  • 性能优化:通常比分开操作性能更好

使用场景:数据转换、文本处理、矩阵操作、条件性展开等需要同时进行映射和扁平化的场景。

http://www.dtcms.com/a/602591.html

相关文章:

  • PPP协议异界冒险:连接神殿的试炼
  • 网站建设的基本条件网站制作协议
  • kotlin build.gradle.kts下修改APK的输出名称
  • 帝国cms地方门户网站模板室内设计效果图素材网站
  • 淘客网站怎么建设小程序商城货源怎么找
  • 在线编译C语言:提升跨平台开发效率
  • 诊断数据库 --- ODX和PDX关系核区别
  • 阿里云申请域名后网站转运网站建设
  • 第13章 函数式语言特性
  • C语言防止反编译工具 | 提高程序安全性并保护源代码
  • 【实战】动态 SQL + 统一 Result + 登录校验:图书管理系统(下)
  • 双缓冲机制:如何避免读写冲突
  • C语言在线编译器网站 | 高效便捷的编程学习平台
  • 你的技术搭子在这里!来openFuyao社区SIG与大咖一起组队
  • 台州自助建站系统做兼职上哪个网站
  • 旅行社应做哪些网站做家电维修网站
  • 网站加入购物车的代码网站视频链接怎么做
  • atsec完成Newland NPT的P2PE PA评估
  • 网站推广预算在线网页爬虫工具
  • 从0开始学区块链第15天——发送和接受ETH
  • 如何批量建站在本地做的网站怎么修改域名
  • 崇左网站搭建给网站开发APP
  • C语言的编译器 | 如何选择适合你的编译器
  • 上位机项目列表
  • 如何用电脑记事本做网站别墅装修设计图片大全 效果图
  • 销售怎么做英文网站建设优化
  • Mac编译C语言 | 学会在Mac上使用终端编译和运行C语言程序
  • Go语言编译器及其使用分析
  • 做建筑的网站产品宣传类网站设计
  • LMV321、LMV358:低功耗轨到轨输入输出 CMOS 运算放大器