本文主要是以下几点
- for...in
- for...of
- filter/map/reduce
for..in 返回的是数组中的下标值,从0开始,for...of 直接返回数组元素,或对象元素
for(let i in this.books){
const book = this.books[i];
result += book.price * book.count;
}
for(let item of this.books){
result += item.price * item.count;
}
例子:挑出小于100的数放在一个新数组里,每个元素*2,将所有newArr的数字相加
let newArr = []
for(let item of arr){
if(item < 100){
newArr.push(i);
}
}
for(let item of arr){
if(item < 100){
newArr.push(item * 2);
}
}
let total=0;
for(let item of newArr){
total += item;
}
console.log(total);
1.filter() 方法创建一个新数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
- filter过滤器中的一个回调函数有一个要求:必须返回一个boolean值
- true:当返回true时,函数内部会自动将这次回调的n加入到新的数组中
- false:当返回false时,函数内部会过滤掉这次的n
2.map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
3.reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce(参数一,参数二)
//preValue 是上一次返回的值
let total = nums.reduce(function(preValue,n){
return preValue + n;
},0);
const arr = [11,234,23,213,455,343,44,5,2];
//let total = arr.filter(n => n<100).map(n => n*2).reduce((pre , n) => pre + n )
let total = arr.filter(function(n){
return n<100;
}).map(function(n){
return n*2;
}).reduce(function(preValue,n){
return preValue + n;
},0);
console.log(total);