在数组 reduce 中显式传递未定义的初始值

Explicit passing initial value as undefined in array reduce

我正在使用数组 reduce 函数测试几个场景。

[1,2].reduce(function(initial ,  val){

        return initial+val;
    } ,1)
    // returns 4 as expected


[1,2].reduce(function(initial ,  val){

    return initial+val;
})
// returns 3

但显式传递 undefined 作为初始值

[1,2].reduce(function(initial ,  val){

    return initial+val;
}, undefined)
// returns NaN.

我觉得这很不寻常。

解释here

Note: If initialValue isn't provided, reduce will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0.

所以你的第二种情况与此类似:

[2].reduce(function(initial, val){
    return initial+val;
}, 1)