美文网首页
数组reduce方法

数组reduce方法

作者: Egde | 来源:发表于2019-04-10 22:01 被阅读0次

概要

Array.prototype.reduce方法接受两个参数。第一个是回调函数,该函数接受四个参数

function(
   accumulator,  // 上次操作返回的结果
   currentValue, // 当前数组元素
   currentIndex, // 当前数组索引
   array  // 被操作的数组
 ) {}

第二个是初始值 arr.reduce(function(acc, current, currntIndex, array) {....}, initial)

执行过程:reduce中的回调函数第一次执行时,将initial传给acc将数组第一个元素传给current. 如果函数体内有return则return的值就传给下次函数执行时的acc, 数组第二个元素就传给current,以此类推。

该函数返回累计处理的结果

reduce结果, 本例return最后的idx

用reduce实现map方法

map方法特性

map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组

map使用

var new_array = arr.map(function callback(item[, idx[, array]]) {
// 返回新数组的元素
}[, thisArg执行 callback 函数时使用的this 值])

使用reduce实现map方法的代码

需要使用到的知识点有闭包,函数call方法, concat方法

function myMap (fn, thisArg) {
    return (list) => {
        if (typeof fn !== 'function') {
            // 做错误处理,抛出
        }
        if (Array.isArray(list)) {
            // 参数非数组,报错抛出
        }
        return list.reduce((a, itm, idx, arr) => {
            return a.concat(fn.call(thisArg, itm, idx, arr))
        }, [])
    }
}
实现效果

一个问题

用reduce求对象数组某属性的平均值

// 如下,求age平均值。使用reduce
arr = [
    {name: 'hh', age: 10},
    {name: 'hh', age: 13},
    {name: 'hh', age: 6},
    {name: 'hh', age: 14},
    {name: 'hh', age: 12}
]
参考

reduce方法
map方法

相关文章

  • js中数组reduce方法的使用和实现

    js中数组reduce方法的使用和实现 reduce方法定义 reduce() 方法对数组中的每个元素执行一个传入...

  • 由对象组成的数组去重方法

    1.定义数组对象: 2.使用数组的reduce()方法 reduce()方法:接收一个函数作为累积器,数组中的每个...

  • javascript高阶函数--未更新完

    pipe compose curring filter --数组的方法 map--数组的方法 reduce--数组...

  • JavaScript迭代

    遍历对象 方法1 方法2 遍历数组 方法1 方法2 方法3 map数组 filter数组 reduce数组 找到某...

  • JavaScript数组的简化

    JavaScript中数组的常用操作之数组的简化 Array.reduce() 方法 Array.reduce(c...

  • JS数组对象去重

    待去重数组 方法一:for循环 方法二:reduce

  • js数组去重

    1. 利用filter方法 chrome执行结果如下 2. 利用reduce方法 reduce() 方法对数组中的...

  • Swift reduce 函数

    reduce Swift中数组的reduce方法用于做序列元素的累加,如数组元素的累加, 函数原型: 参数: in...

  • js笔记

    数组的reduce reduce()方法接收一个函数callback作为累加器,数组中的每个值(从左到右)开始合并...

  • Swift高阶函数小计

    用 reduce 方法一次求出数组中奇数的和、以及偶数乘积 reduce 方法实现 map 的功能 求一个数组中偶...

网友评论

      本文标题:数组reduce方法

      本文链接:https://www.haomeiwen.com/subject/beraiqtx.html