数组遍历的方法以及区别

1.for循环
避免重复获取数组长度,当数组较大时优化明显
for(let j = 0 , len = arr.length ; j < len ; j++ ){

  }

2.foreach循环
遍历数组中的每一项,没有返回值,对原数组(对基础数据类型无法修改,引用数据类型可以修改)没有影响,不支持IE
const array = [1, 2, 3, 4];
array.forEach((item,index,arr) => {
item = item * 3
})
console.log(array); // [1,2,3,4]
3.map循环
有返回值,可以return出来
map的回调函数中支持return返回值;return的是啥,相当于把数组中的这一项变为啥(并不影响原来的数组,只是相当于把原数组克隆一份,把克隆的这一份的数组中的对应项改变了);
var ary = [12,23,24,42,1];
var res = ary.map(function ( item,index,ary ) {
return item*10;
})
console.log(res);//-->[120,230,240,420,10]; 原数组拷贝了一份,并进行了修改
console.log(ary);//-->[12,23,24,42,1]; 原数组并未发生变化
4.forof遍历
只能对数组使用,直接得到值
let arr = [1, 2, 3, 4, 5, 6, 7]
let arr2 = new Array();
for (let val of arr) {
if (val > 5) {
arr2.push(val)
}
}
console.log(arr2) // [6,7]
5.filter遍历
不会改变原始数组,返回新数组
arr.filter( (item,index,arr) => {
return item
})
6.every遍历
对原数组给定一个函数,如果每一项都符合条件则返回true,否则返回false
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.every( function( item, index, array ){
return item > 3;
}));
// false
7.some遍历
对原数组给定一个函数,如果有一项都符合条件则返回true,否则返回false
var arr = [ 1, 2, 3, 4, 5, 6 ];
console.log( arr.some( function( item, index, array ){
return item > 3;
}));
// true
8.reduce
从左至右操作数组中的每一个值,参数为 前一项的值 下一项的值 索引 数组
arr.reduce( ( previousValue, currentValue,index,array ) => {
return previousValue + currentValue
})
9.reduceRight
从右至左操作数组每一项的值,参数和reduce相同,但是方向相反
arr.reduce( ( previousValue, currentValue,index,array ) => {
return previousValue + currentValue
})
10.find
find()方法返回数组中符合筛选条件的第一个元素,否则返回undefined
let arr = [1,2,3,4,5,8]
arr.find( (item)=>{
return item > 5
})
// 8

原文地址:https://www.cnblogs.com/vancissell/p/12929391.html