目录
1.普通遍历
对象.forEach( ):遍历数组中的每一项,并为每一项执行提供的函数。它不会改变原数组。
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(item, index) {
console.log(item, index)
})
2.对元素统一操作
对象.map( ):通过调用给定函数在每个元素上,创建一个新的数组,其结果是该函数在每个元素上的返回值。
let arr = [1, 2, 3, 4, 5]
let newArr = arr.map(function(item) {
return item * 2
})
console.log(newArr); // [2, 4, 6, 8, 10]
3.查找符合条件的元素
对象.filter( ):用于创建一个新的数组,包含通过所提供函数实现的测试的所有元素。
let arr = [1, 2, 3, 4, 5]
let newArr = arr.filter(function(item) {
return item > 2
})
console.log(newArr); // [3, 4, 5]
4.查询符合条件的元素,返回索引
对象.findIndex( ):用于返回数组中满足提供的测试函数的第一个元素的索引。
let arr = [1, 2, 3, 4, 5]
let index = arr.findIndex(function(item, index) {
return index > 1
})
console.log(index) // 2
5.遇到不符合的对象会停止
对象.evening( ):用于检查所有元素是否都符合提供的测试函数。如果有任何一个元素不通过测试,该方法立即返回false,并停止运行其余的测试。
let arr = [1, 2, 3, 4, 5]
let result = arr.every(function(item) {
return item > 1
})
console.log(result); // false
6.找到符合的对象就停止
对象.some( ):用于检查是否有至少一个元素通过提供的测试函数。如果有任何一个元素通过测试,该方法立即返回true,并停止运行其余的测试。
let arr = [1, 2, 3, 4, 5]
let result = arr.some(function(item) {
return item > 3
})
console.log(result); // true