map, reduce, filter 等高阶函数

栏目: JavaScript · 发布时间: 6年前

内容简介:上篇其实还有一篇关于常见的高阶函数有:

上篇其实还有一篇关于 闭包 的文章,由于在前几篇中已经涉及到了相关方面,因此 闭包 文章暂时搁置一下。换个新话题:

内容

高阶函数 :Higher-order function;

  • 至少满足以下条件:
      1. 函数可以作为参数被传递;
      1. 函数可以作为返回值被输出。

常见的高阶函数有: MapReduceFilterSort

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]
复制代码

筛选出符合条件的项,组成新数组。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Seasoned Schemer

The Seasoned Schemer

Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00

drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具