我很好奇为什么在数组上使用.reduce时,在以下代码中始终未定义previousValue:
码:
[2,2,2,3,4].reduce(function(previousValue, currentValue){
console.log("Previous Value: " + previousValue);
console.log("Current Value: " + currentValue);
},0)
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
可以在这里找到一个小提琴:http://jsfiddle.net/LzpxE/
der*_*sse 43
您需要返回一个值才能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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6266 次 |
| 最近记录: |