题解 | #Array.reduce#

Array.reduce

http://www.nowcoder.com/practice/213d0ef21cb841de8cf69fcc5ea60eb6

09_Array.reduce

本题考点:Array.reduce

根据题目要求,实现一个仿Array.reduce功能的"Array._reduce"函数,并且需要将”_reduce“函数挂载在Array的原型对象上。根据Array.reduce的特点有:

  1. 接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值
  2. 可以接收一个初始值,当没有初始值时,默认初始值为数组中的第一项

实现该函数的核心步骤有:

  1. 在Array的原型对象上添加”_reduce“函数
  2. ”_reduce“函数第一个参数为回调函数,第二个参数为初始值
  3. 进入数组长度的循环体中
  4. 当初始值为空时,首个被加数为数组的第一项
  5. 当初始值不为空时,首个被加数为初始值

参考答案

Array.prototype._reduce = function(fn, prev) {
    for(let i=0 ; i<this.length ; i++) {
        if(prev === undefined) {
            prev = fn(this[i], this[i+1], i+1, this)
                ++i
        } else {
            prev = fn(prev, this[i], i, this)
        }
    }
    return prev
}

全部评论

相关推荐

面了100年面试不知...:今年白菜这么多,冬天可以狂吃了
点赞 评论 收藏
分享
评论
8
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务