我正在尝试将数组减少为其偶数值的总和。我一直在检查 MDN 的文档 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
这表示,如果提供了初始值,那么它不会跳过第 0 个索引,实际上它将从索引 0 开始。我的问题是,reduce 是从索引 1 开始的。因此,我的结果是不正确的。我确信我错误地阅读了该文件或误解了它。这是我指的注释 - “注意:如果未提供initialValue,则reduce()将从索引1开始执行回调函数,跳过第一个索引。如果提供了initialValue,它将从索引0开始。”
这是我的代码。
var array = [1,2,3,4,6,100];
var initialValue = 0;
var value = array.reduce(function(accumulator, currentValue, currentIndex, array, initialValue) {
//console.log(accumulator);
if( currentValue % 2 === 0) {
accumulator += currentValue;
//return accumulator;
}
return accumulator;
});
console.log(value);
Run Code Online (Sandbox Code Playgroud)
显然,我看到的结果是 113 而不是 112。我猜,这是因为累加器的值已经是 1。因此,它最初会加 1。
如果你再看一下文档,你会发现 the callbackFnonly 最多有 4 个变量,而且 theinitialValue必须在第二个参数上
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
^ ^
Run Code Online (Sandbox Code Playgroud)
112这是按预期返回的小型固定版本
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
^ ^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4478 次 |
| 最近记录: |