JS 中 高阶函数map reduce

JS 中 高阶函数map、reduce

  • map

  1.      定义和用法:

          map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

          map() 方法按照原始数组元素顺序依次处理元素。

  2. 调用map()的一定是Array类型,map()的返回值也是一个Array
  3. 语法:arr.map(function(currentValue,index,arr)),一般index、arr可省略 
  4. 注意:map()并不会改变原始数组,且map不会对空数组进行检测 

    举个栗子:

function pow(x) {
    return x + 5;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); // [6, 7, 8, 9, 10, 11, 12, 13, 14]
console.log(results);

    再举个栗子:

function pow(x) {
    return x * x;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var results = arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
console.log(results);

总结:

     一个array类型的变量 arr,arr调用Array内部定义函数map(),而参数是function(),arr数组中的元素为原始数组元素,map()方法按照原始数组元素顺序依次调用并执行function(),把处理后的结果封装成一个新的Array作为返回值返回。

  • reduce

  1. 定义和用法:

    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

    reduce() 可以作为一个高阶函数,用于函数的 compose。

  2. 语法:

    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  3. 注意:reduce() 对于空数组是不会执行回调函数的。

        栗子又来了:计算数组元素相加后的总和,结果125

var numbers = [65, 44, 12, 4];
function getSum(total, num) {
    return total + num;
}
var result = numbers.reduce(getSum);
console.log(result);

        哈哈,再来一个:[1, 3, 5, 7, 9]变换成整数13579

var arr = [1, 3, 5, 7, 9];
var result = arr.reduce(function (x, y) {
    return x * 10 + y;
}); 
console.log(result);

     注:参考廖雪峰老师的JavaScript教程和菜鸟JavaScript教程


猜你喜欢

转载自blog.csdn.net/qq_42465672/article/details/80712089