在 javascript 中减少初始值

2024-01-06

我正在尝试将数组减少为其偶数值的总和。我一直在检查 MDN 的文档 -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce 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);

显然,我看到的结果是 113 而不是 112。我猜,这是因为累加器的值已经是 1。因此,它最初会加 1。


如果你再看一下该文档,你会发现callbackFn最多只需要 4 个变量,并且initialValue必须在第二个参数上

arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
                   ^                                               ^

这是返回的小修正版本112正如预期的那样

var array = [1,2,3,4,6,100];
var initialValue = 0;
var value = array.reduce(function(accumulator, currentValue, currentIndex, array) {
    //console.log(accumulator);
    if( currentValue % 2 === 0) {
      accumulator += currentValue;
      //return accumulator;
    }
    return accumulator;
}, initialValue);
console.log(value);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 javascript 中减少初始值 的相关文章