版本 1:
var c = [ '##' ]
console.log(c.reduce(function(a,b){
return b.length
}, 0)) // 2
版本 2:
var c = [ '##' ]
console.log(c.reduce(function(a,b){
return b.length
})) // "##"
我很好奇,如果我不提供初始值,为什么 length 方法不起作用,正如您在版本 2 中看到的那样?
那么有人能告诉我在这种情况下为什么我需要提供长度方法的初始值才能工作吗?
最佳答案
版本 1
The first time the callback is called, previousValue and currentValue can be one of two values. If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array.
在版本 #1 中,提供了 initialValue
。因此,根据文档,previousValue
被指定为 initialValue
因此,对于第一次迭代:
previousValue = initialValue
previousValue = 0
nextValue
是数组中的第一个元素。
nextValue = '##'
所以,返回值2。
版本 2不言自明
If the array is empty and no initialValue was provided, TypeError would be thrown. If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.
关于javascript - 在 Array#reduce 中设置 initialValue 与不设置 initialValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34874556/