需求:有这样一个数组[10, 20, 110, 200, 60, 30, 40]
1.筛选出数组中小于100的元素
2.将筛选出的每个元素的值x2
3.完成第2步之后,将数组中的所有元素加起来
?
如果我们还没接触过filter、map、reduce,那么就是用for循环
<script>
list = [10, 20, 30, 40, 60, 110, 200]
newList = []
newList2 = []
total = 0
// 第1次for循环把小于100的数加入新的数组newList
for (item of list){
if (item<100){
newList.push(item)
}
}
// 第2次for循环把所有的元素值乘以2
for (item of newList){
newValue = item * 2
newList2.push(newValue)
}
// 第3次for循环把数组中的全部元素加起来
for (item of newList2){
total += item
}
console.log(total)
</script>
以上写起来非常繁琐,还要定义很多变量,代码阅读起来也不是很好,其实我们有更好的方式,下面介绍
?
检测数值元素,并返回符合条件所有元素的数组。
?
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素
?
注意
filter() 不会对空数组进行检测。
filter() 不会改变原始数组。
?
array.filter(function(currentValue,index,arr), thisValue)
参数说明如下:
使用filter函数筛选出[10, 20, 110, 200, 60, 30, 40]小于100的
list = [10, 20, 30, 40, 60, 110, 200]
newList = list.filter(function (n) {
return n < 100
})
console.log(newList)
打印结果
[10, 20, 30, 40, 60]
?
map通过指定函数处理数组的每个元素,并返回处理后的数组。
?
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
?
注意
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
?
array.map(function(currentValue,index,arr), thisValue)
参数说明如下:
将数组[10, 20, 30, 40, 60]中的每个元素值乘以2
<script>
list = [10, 20, 30, 40, 60]
newList = list.map(function (n) {
return n * 2
})
console.log(newList)
</script>
打印结果
[20, 40, 60, 80, 120]
?
reduce将数组元素计算为一个值(从左到右)
?
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意:reduce() 对于空数组是不会执行回调函数的。
?
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数说明如下:
计算数组之和[20, 40, 60, 80, 120]
<script>
list = [20, 40, 60, 80, 120]
newList = list.reduce(function (total, n) {
return total + n
}, 0)
console.log(newList)
</script>
打印结果
320
?
使用filter和map和reduce完成案例上面我们分别介绍了3个高阶函数,接下来结合起来使用
?
<script>
list = [10, 20, 110, 200, 60, 30, 40]
newList = list.filter(function (n) {
return n < 100
}).map(function (n) {
return n * 2
}).reduce(function (total, n) {
return total + n
})
console.log(newList)
</script>
?
<script> list = [10, 20, 110, 200, 60, 30, 40] newList = list.filter(n => n < 100).map(n => n * 2).reduce((total, n) => total+n); console.log(newList) </script>
以后我们就可以一行代码完成上面的需求,而不需要使用for循环了
JavaScript(1)高阶函数filter、map、reduce
原文:https://blog.51cto.com/u_15183212/2962303