I found a very useful function reduce
, and I'm using it, but I'm not sure if I understand it properly. Can anyone help me to understand this function?
Example:
var arr = [ 1, 2, 3, 4, 5, 6 ];
arr.reduce(function(p,n){
return p + n;
}, 0);
// Output 21
This is my understanding: reduce
loops through every element of the array and returns previous + current value
. Ex. 0 + 1
, 1 + 2
etc. In this case this function will return:
[0] - return 1
[1] - return 3
[2] - return 5
[3] - return 7
[4] - return 9
[5] - return 11
What next? Why does it give the result 21
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…