定义和用法
-
map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。注意: map() 不会对空数组进行检测。map() 不会改变原始数组。
-
filter
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。注意: filter() 不会改变原始数组。
-
reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。reduce() 对于空数组是不会执行回调函数的。
代码比较
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let arr2 = [
{ id: 1, name: 'test1' },
{ id: 2, name: 'test2' },
{ id: 3, name: 'test3' },
{ id: 4, name: 'test4' },
{ id: 5, name: 'test5' }
]
let arrMap = arr1.map((item, index) => item > 2)
let arrFilter = arr1.filter((item, index) => item > 2)
let arrTotal = arr1.reduce((total, current, index) => {
return total + current
}, 0)
console.log(arrMap) //[false, false, false,false, false, true,true, true, true,true]
console.log(arrFilter) //[ 6, 7, 8, 9, 10 ]
console.log(arrTotal) // 55
let arrMap = arr2.map((item, index) => item.name)
let arrFilter = arr2.filter((item, index) => item.id > 4)
let arrTotal = arr2.reduce((total, current, index) => {
return total + current.id
}, 0)
console.log(arrMap) //[ 'test1', 'test2', 'test3', 'test4', 'test5' ]
console.log(arrFilter) //[{ id: 5, name: 'test5' }]
console.log(arrTotal) // 15
总结
主要从以下几个点理解:
- map主要时用来构造我们需要的特定数据格式,比如像每个item添加属性,或者单纯获取某个属性值
- filter主要是用来过滤和筛选满足特定的条件下的值
- reduce主要是用于计算,当然他还有一些高级用法,此处不予说明