• home > webfront > ECMAS > javascript >

    手搓一个reduce就能门清:initialValue,previousValue,currentValue

    Author:zhoulujun Date:

    reduce,是es5里面新增的函数,但是并不常用而且掌握,也并不容易。reduce函数使用注意事项,避免里面的坑。活学活用

    reduce,是es5里面新增的函数,但是并不常用而且掌握,也并不容易。

    今天查下文档,又被坑了一把!

    看了下微软的教材:https://docs.microsoft.com/en-us/scripting/javascript/reference/reduce-method-array-javascript,解释如下:

    Screen Shot 2017-07-12 at 16.01.13.png

    误以为,previousValue和currentValue是固定,取的。

    比如:

    let d=[1,2,3,4].reduce(function (prev,current,currentindex) {
    
       console.log('___prev:'+prev+";current:"+current+';currentindex:'+currentindex);
        return current;
    });

    我以为prev是固定去1,2,3,4。实际是

    previousValue,如果没有传 initialValue,就是取第一项为初始值,函数从数组二项开始循环。

    否则previousValue就为initialValue,循环从第一项开始。 

    循环到第二项,previousValue为 第一次循环的返回值。

    First Call to the Callback Function

    The first time the callback function is called, the values provided as arguments depend on whether the reduce method has an initialValueargument.

    If an initialValue is provided to the reduce method:

    • The previousValue argument is initialValue.

    • The currentValue argument is the value of the first element present in the array.

      If an initialValue is not provided:

    • The previousValue argument is the value of the first element present in the array.

    • The currentValue argument is the value of the second element present in the array.



    如何实现一个reduce函数?

    Array.prototype.myReduce = function (callback, preValue) {
      if (typeof callback !== 'function') {
        throw new Error(`${callback} is not a function !`)
      }
      let index = 0
      let len = this.length
      if (preValue === undefined || preValue === null) {
        index = 1
        preValue = this[0]
      }
    
      for (; index < len; index++) {
        preValue = callback(preValue, this[index], index, this)
      }
      return preValue
    }




    查看MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    • accumulator

    • The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).



    转载本站文章《手搓一个reduce就能门清:initialValue,previousValue,currentValue》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/js/2017_0712_8029.html