let nums = [20, 40, 30, 555, 120, 50];
let new1Nums = nums.filter(function(n) {
return n < 100;
});
console.log(new1Nums); //[20, 40, 30, 50]
let new2Nums = new1Nums.map(function(n) {
return n * 2;
});
console.log(new2Nums); //[40, 80, 60, 100]
let new3Nums = new2Nums.reduce(function(pre,n) {
return pre + n;
}, 0); // 0: 第一次pre的值
console.log(new3Nums); //280
简化:
let nums = [20, 40, 30, 555, 120, 50];
let newNums = nums.filter(function(n) {
return n < 100;
}).map(function(n) {
return n * 2;
}).reduce(function(pre,n) {
return pre + n;
}, 0);
console.log(newNums); //280
配合箭头函数:
let nums = [20, 40, 30, 555, 120, 50];
let newNums = nums.filter(n => n < 100 ).map( n => n * 2 ).reduce((pre,n) => pre + n )
console.log(newNums); //280