es6高阶函数filter、map、reduce的使用:
//1、需求:筛选出数组中数字小于100的数字。
//2、需求:将数组中的每个数字乘以3.
//3、需求:数组中的数组汇总求和。
let nums = [10, 20, 50, 88, 99, 32, 288, 12, 266, 22]
/**
* 旧的写法:
* @type {*[]}
*/
let old_newnums = []
//1、筛选出数组中数字小于100的数字。
for (let i = 0; i < nums.length; i++) {
if (nums[i] < 100) {
old_newnums.push(nums[i])
}
}
//2、将数组中的每个数字乘以3.
let old_newnums1 = []
for (let i = 0; i < old_newnums.length; i++) {
old_newnums1.push(old_newnums[i] * 3)
}
//3、数组中的数组汇总求和。
let old_newnums2 = 0
for (let i = 0; i < old_newnums1.length; i++) {
old_newnums2 += old_newnums1[i]
}
console.log("旧的写法:", old_newnums2);
/*---------------------------------新的写法-------------------------------------------*/
/**
* 定义:filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
* 注意:filter不会对空数组进行检测
* 注意:filter不会改变原数组
* filter中的回调函数有一个要求:必须返回一个bollean值
* true : 当返回true时,函数内部会自动将这次回调的n加入到新的数组中
* false: 当返回fasle时,函数内部会过滤掉这次的n
* @type {*[]}
*/
let new_nums = nums.filter(function (n) {
return n < 100
})
/**
* map 映射函数
* 定义: map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。map() 方法按照原始数组元素顺序依次处理元素。
* 注意: map() 不会对空数组进行检测。
* 注意: map() 不会改变原始数组。
* @type {number[]}
*/
let new_nums1 = new_nums.map(function (n) {
return n * 3
})
/**
* 定义:reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 可以作为一个高阶函数,用于函数的 compose。
* reduce() 对于空数组是不会执行回调函数的。
* reduce(function(上一次结果 初始值为默认值,数组的n),默认值=0) 对数组中所有的内容进行汇总。
* @type {number}
*/
//
let new_nums2 = new_nums1.reduce(function (prev, n) {
return prev + n
}, 0)
console.log("新的写法1.0:", new_nums2);
//或者可以写成
let new_writeNums = nums.filter(function (n) {
return n < 100
}).map(function (n) {
return n * 3
}).reduce(function (prev, n) {
return prev + n
}, 0)
console.log("新的写法2.0:", new_writeNums);