【JavaScript】数组遍历 - forEach、map、filter、reduce、some、every

JavaScript 提供了多种数组遍历方法,以下是常见的几种方法:

  1. forEach:遍历数组中的每个元素,并执行指定的回调函数,没有返回值。
array.forEach((element, index, array) => {
// do something
})
示例:打印数组中的每个元素
const array = [1, 2, 3, 4, 5]
array.forEach(item => {
console.log(item) // 1 2 3 4 5
})
  1. 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) // [2, 4, 6, 8, 10]
  1. 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) // [2, 4]
  1. 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) // 初始值为 5
console.log(sum) // 20
const array = [1, 2, 3, 4, 5]
const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue) // 不指定初始值,则从数组的第一个元素开始累加
console.log(sum) // 15
  1. 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) // true
  1. 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) // false
  1. 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) // 6
  1. 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) // 1

关于数组的遍历方法就介绍到这里了,希望对大家有所帮助。

posted @   夏洛的网08  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示