JavaScript 提供了多种数组遍历方法,以下是常见的几种方法:
- forEach:遍历数组中的每个元素,并执行指定的回调函数,没有返回值。
| array.forEach((element, index, array) => { |
| |
| }) |
示例:打印数组中的每个元素
| const array = [1, 2, 3, 4, 5] |
| array.forEach(item => { |
| console.log(item) |
| }) |
- map:遍历数组中的每个元素,并执行指定的回调函数,返回一个新数组。
| const newArray = array.map((element, index, array) => { |
| |
| }) |
示例:原数组的每一项乘以 2
| const array = [1, 2, 3, 4, 5] |
| const newArray = array.map(item => item * 2) |
| console.log(newArray) |
- filter:根据指定的条件过滤数组中的元素,返回一个新数组,新数组只包含满足条件的元素。
| const resultArray = array.filter((element, index, array) => { |
| |
| }) |
示例:过滤数组中的偶数
| const array = [1, 2, 3, 4, 5] |
| const resultArray = array.filter(item => item % 2 === 0) |
| console.log(resultArray) |
- reduce:对数组中的每个元素依次执行指定的回调函数,将其结果汇总为单个返回值。
| const result = array.reduce((accumulator, currentValue, currentIndex, array) => { |
| |
| }, initialValue) |
示例:数组求和
| const array = [1, 2, 3, 4, 5] |
| const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 5) |
| console.log(sum) |
| const array = [1, 2, 3, 4, 5] |
| const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue) |
| console.log(sum) |
- some:用于判断数组中是否存在满足条件的元素,返回一个布尔值。
| const result = array.some((element, index, array) => { |
| |
| }) |
示例:判断数组中是否存在大于 5 的元素
| const array = [6, 0, 2, 5, 9] |
| const result = array.some(item => item > 5) |
| console.log(result) |
- every:用于判断数组中是否所有元素都满足条件,返回一个布尔值。
| const result = array.every((element, index, array) => { |
| |
| }) |
示例:判断数组中是否所有元素都大于 5
| const array = [6, 0, 2, 5, 9] |
| const result = array.every(item => item > 5) |
| console.log(result) |
- find:用于查找数组中满足条件的第一个元素,返回该元素,如果没有找到满足条件的元素,则返回 undefined。
| const result = array.find((element, index, array) => { |
| |
| }) |
示例:查找数组中第一个大于 5 的元素
| const array = [0, 6, 2, 5, 9] |
| const result = array.find(item => item > 5) |
| console.log(result) |
- findIndex:用于查找数组中满足条件的第一个元素的索引,返回该索引,如果没有找到满足条件的元素,则返回 -1。
| const result = array.findIndex((element, index, array) => { |
| |
| }) |
示例:查找数组中第一个大于 5 的元素的索引
| const array = [0, 6, 2, 5, 9] |
| const result = array.findIndex(item => item > 5) |
| console.log(result) |
关于数组的遍历方法就介绍到这里了,希望对大家有所帮助。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!