• home > webfront > ECMAS > javascript >

    js里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.





    查看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).



    转载本站文章《js里reduce函数里面的坑!区分initialValue,previousValue,currentValue》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/js/2017_0712_8029.html