关于数组reduce函数中初始值的问题

2024-04-07

我实际上遇到了一个问题,更多的是这个作业问题的说明,如下所示:

将collection减少为一个值,该值是通过iteratee运行collection中每个元素的累积结果, 其中每个连续调用都会提供前一个调用的返回值。 如果未提供累加器,则集合的第一个元素将用作初始值。如果未提供起始参数,则将起始值设置为第零个索引。

这是应该发生的情况的细分:

// reduce([1,2], function(stored,current) {
//  return stored + current;
// }); → 3
// reduce([1,2], function(stored,current) {
//  return stored + current;
// },1); → 4

如果我正确阅读指令,则起始参数是开始累积的初始值,不是吗?如果在调用函数时未提供起始参数,则索引 0 处的值将是起始值。唯一的问题是,当在未提供起始参数的情况下获取该值时,第一个 val 会累积两次,这会返回意外的结果。

到目前为止,我已经研究了reduce 方法和从不同索引开始的不同方法。 看起来如果没有提供起始值,我需要将初始值设置为 array[0] 然后 array.slice(1) 并从那里减少,但是,我不太确定这就是作业所说的去做。

我不太明白 if 之间的区别accumulator is not provided如果一个start parameter is not provided。如果没有提供累加器,那么初始值不是输入数组中的第一个值,并且起始索引是 1 吗?所以不要将第一个值加/减两次?

这是我的代码:

function reduce(array, callback, start) { 
    return array.reduce((acc, val, start) => {
      //if start value not provided, start value is index 0
        return callback(acc, val) }, start || array[0])
}

这是结果。

//start provided as -1, result correct
var difference = function(tally, item) {return tally - item; };
var total = reduce([1, 2, 3], difference, -1); // expected -> -7 got -7

//start provded as 2, result correct
var add = function(tally, item) {return tally + item; };
var total = reduce([1, 2, 3], add, 2); // expected -> 8 got 8

//start not provided, first index used as start, as per instructions
//therefore first index is added twice, giving wrong answer
var add = function(tally, item) {return tally + item; };
var total = reduce([1, 2, 3], add); // expected -> 6 got 7

//start not provided, first index used as start, as per instructions
//therefore first index is subtracted twice, giving wrong answer
var difference = function(tally, item) { return tally - item; };
var total = reduce([1, 2, 3], difference); // -> expected -4 got -5

是的你是对的。如果没有提供初始累加器,则将第一个数组元素作为累加器,并且将从第二个元素开始调用回调。

您的代码复制了第一个数组元素,因为它将它作为累加器传递。还使用||这里很危险,它会失败,例如0。我只想这样做:

 function reduce(array, callback, start) { 
   return array.reduce(callback, start);
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于数组reduce函数中初始值的问题 的相关文章

随机推荐