我实际上遇到了一个问题,更多的是这个作业问题的说明,如下所示:
将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