javascript - 在 Array#reduce 中设置 initialValue 与不设置 initialValue

标签 javascript 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
})) // "##"

我很好奇,如果我不提供初始值,为什么 length 方法不起作用,正如您在版本 2 中看到的那样?

那么有人能告诉我在这种情况下为什么我需要提供长度方法的初始值才能工作吗?

最佳答案

版本 1

来自 MDN Docs for Array#reduce

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/

相关文章:

javascript - 将 html 注入(inject)现有页面而不受 css 影响

javascript - 在窗口调整大小时调整子 div 元素的大小以适应父 div

android - 如何减少android中的 Activity 数量?

javascript - 缩小并扁平化一个物体的物体

javascript - 如何将字符串作为函数传递到react-router-dom Route中?

javascript - 如何将值转换为对象数组

php - 为什么这个 Javascript 在 Firefox 和 Explorer 中运行一次,而在 Opera 中运行 3 次?

python - 尝试理解python中reduce的功能

javascript - 减少条件未定义的返回

javascript - 查找 JavaScript 数组中缺失的数字