JavaScript .reduce, previousValue is always undefined -


i curious why previousvalue undefined in following code when using .reduce on array:

code:

[2,2,2,3,4].reduce(function(previousvalue, currentvalue){     console.log("previous value: " + previousvalue);     console.log("current value: " + currentvalue); },0) 

output:

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  

a fiddle can found here: http://jsfiddle.net/lzpxe/

you need return value in order use reduce correctly. returned value used in next step.

like:

[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   

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -