在 Array#reduce 中设置 initialValue 与不设置 initialValue
Setting initialValue vs. Not setting initialValue in Array#reduce
版本 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
})) // "##"
我很好奇,如果我不提供您在版本 2 中看到的初始值,为什么 length 方法不起作用?
所以有人能告诉我在这种情况下为什么我需要提供长度方法的初始值才能工作吗?
版本 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.
版本 2self-explanatory
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.
版本 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
})) // "##"
我很好奇,如果我不提供您在版本 2 中看到的初始值,为什么 length 方法不起作用?
所以有人能告诉我在这种情况下为什么我需要提供长度方法的初始值才能工作吗?
版本 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.
版本 2self-explanatory
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.