Подтвердить что ты не робот

JavaScript.reduce, previousValue всегда undefined

Мне любопытно, почему previousValue всегда undefined в следующем коде при использовании .reduce в массиве:

код:

[2,2,2,3,4].reduce(function(previousValue, currentValue){
    console.log("Previous Value: " + previousValue);
    console.log("Current Value: " + currentValue);
},0)

Вывод:

Previous Value: 0 (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 3 (index):24
Previous Value: undefined (index):23
Current Value: 4 

Сценарий можно найти здесь: http://jsfiddle.net/LzpxE/

4b9b3361

Ответ 1

Вам нужно вернуть значение, чтобы правильно использовать reduce. Возвращаемое значение будет использовано на следующем шаге.

Как

[0,1,2,3,4].reduce(function(previousValue, currentValue) {
     return previousValue + currentValue;
});
// returns 10 in total, because
// 0 + 1 = 1 -> 1 + 2 = 3 -> 3 + 3 = 6 -> 6 + 4 = 10