1、filter()
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
参数为一个回调函数,回调函数的参数为数组中具体的值,返回值为boolean类型。
当该数组中的值满足回调函数返回值为true时,将该值返回到新的数组中;不满足则不返回,最后得到一个新的数组。
const nums = [15, 70, 80, 120, 95, 110, 100, 105]
//filter()函数
let newNums = nums.filter(function (n) {
return n < 100;
});
console.log(newNums);

2、map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。map() 方法按照原始数组元素顺序依次处理元素。
参数为回调函数,回调函数的参数为数组中的值,返回值为数组的值经过处理后的值,将该值返回到新的数组中
const nums = [10, 20, 30, 40]
//map()函数
let newNums = nums.map(function (n) {
return n * 2;
});
console.log(newNums);
3、reduce()
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 可以作为一个高阶函数,用于函数的 compose。
reduce()方法的参数有两个,第一个参数为回调函数function(preValue, n),其中preValue为回调函数的返回值,n为数组中的值。
而reduce()方法的第二个参数为第一次调用回调函数时,preValue的值,一般为0。
const nums = [10, 20, 30, 40, 50, 60]
//reduce()函数
//preValue为上一次reduce()函数的返回值,即preValue+n
//第1次执行:preValue = 0, n = 10
//第2次执行:preValue = 10, n = 20
//第3次执行:preValue = 30, n = 30
//第4次执行:preValue = 60, n = 40
//第5次执行:preValue = 100, n = 50
//第6次执行:preValue = 150, n = 60
//第7次,数组中已经没有数值,返回上次的preValue+n
let total = nums.reduce(function (preValue, n) {
return preValue + n;
}, 0);
console.log(total);
![]()
2552

被折叠的 条评论
为什么被折叠?



