JavaScript 提供了多种数组遍历方法,以下是常见的几种方法:
- 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
})
- 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]
- 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]
- 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
- 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
- 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
- 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
- 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
关于数组的遍历方法就介绍到这里了,希望对大家有所帮助。