一、filter遍历数组:查询数组,查询数组的指定的值(>,<,=)
const arr = [10,20,111,222,444,40,50]
1.使用for循环:
let newArr = []
for(let n of arr){
if(n < 100){
newArr.push(n)
}
}
console.log(newArr);//[10,20,40,50]
2.使用filter循环:
let newArr = arrs.filter(function(n){
return n < 100
})
console.log(newArr);//[10,20,40,50]
二、map遍历数组,并返回一个值(用于计算)
数组 let newArr=[10,20,40,50],把数组中的每个元素*2,再添加到新的数组中
map函数会将回调函数返回的值作为新值传入到新数组中
1.使用for循环:
let new2Arr = []
for (let n of newArr){
new2Arr.push(n * 2)
}
console.log(new2Arr);//[20,40,80,100]
2.使用map循环:
let new2Arr = newArr.map(function(n){
return n*2
})
console.log(new2Arr);//[20,40,80,100]
三、reduce循环数组:求和(每个元素单独操作/判断,并返回结果);
数组 let new2Arr=[20,40,80,100]
1.使用for循环:
let total = 0
for(let n of new2Arr){
total += n
}
console.log(total);//240
2.使用reduce:
语法:reduce(function(preValue,n),initiaValue)
使用reduce必须要传入这几个参数,一个回调函数和一个初始化值initiaValue。reduce也会遍历数组,当没有传入初始值时,第一个preValue是数组中第一个元素,n数组是第二个元素。但是当传入初始值(initiaValue)后,第一个preValue将是initivalValue,n将是数组中的第一个元素。从第二次开始,后面的preValue取决于回调函数中返回的值。
执行步骤如下:
new2Arr.reduce(function(preValue,n){
console.log('preValue=',preValue,'n=',n);
return 100
},0)
//第一次 preValue=0 n=20
//第二次 preValue=100 n=40
//第三次 preValue=100 n=80
//第四次 preValue=100 n=100
let total = new2Arr.reduce(function(preValue,n){
return preValue + n
},0)
console.log(total);//240
//第一次 preValue=0 n=20
//第二次 preValue=20 n=40
//第三次 preValue=60 n=80
//第四次 preValue=140 n=100
//return 240