map, reduce, filter 等高阶函数
初衷
上篇其实还有一篇关于闭包
的文章,由于在前几篇中已经涉及到了相关方面,因此闭包
文章暂时搁置一下。换个新话题:
内容
高阶函数:Higher-order function;
- 至少满足以下条件:
-
- 函数可以作为参数被传递;
-
- 函数可以作为返回值被输出。
-
常见的高阶函数有: Map
、Reduce
、Filter
、Sort
;
1. Map
array.map(function(currentValue,index,arr), thisValue)
map() 不会改变原始数组
[55,44,66,11].map(function(currentValue,index,arr){
console.log(currentValue); //map() 方法按照原始数组元素顺序依次处理元素
console.log(index);
console.log(arr);
});
让数组通过某种计算得到一个新数组
var newArr = [55,44,66,11].map(function(item,index,arr){
return item *10;
});
console.log(newArr);//[550, 440, 660, 110]
2. reduce
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
initialValue
:传递给函数的初始值;
让数组中的前项和后项做某种计算,并累计最终值。
var newArr = [15.5, 2.3, 1.1, 4.7].reduce(function(total,num){
return total + Math.round(num);//对数组元素进行四舍五入并计算总和
}, 0);
console.log(newArr);//24
reduce() 对于空数组是不会执行回调函数
3. filter
array.filter(function(currentValue,index,arr), thisValue)
filter() 不会改变原始数组
var newArr = [32, 33, 12, 40].filter(function(item){
return item > 32;
});
console.log(newArr);//[33, 40]
筛选出符合条件的项,组成新数组。
4. forEach
array.forEach(function(currentValue, index, arr), thisValue)
map() 与 forEach() 语法一致,能用`forEach()`做到的,`map()`同样可以,但是存在区别。
- 区别:
forEach()
返回值是undefined
,不可以链式调用;map()
返回一个新数组,原数组不会改变.
结语
业精于勤而荒于嬉,行成于思而毁于随。
转载自:https://juejin.cn/post/6844903848918990856