为什么在JavaScript中第一次迭代后数组会减少函数更改参数?

时间:2016-08-01 02:09:50

标签: javascript parameters parameter-passing reduce

包含实际结果的示例代码和浏览器版本(用户代理):

> [{count:1},{count:2},{count:3}].reduce(function(prev,curr){console.log(arguments);return 5;})
[Object, Object, 1, Array[3]]
[5, Object, 2, Array[3]]
5
> navigator.appVersion
"5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"

包含预期结果的示例代码:

-> [{count:1},{count:2},{count:3}].reduce(function(prev,curr){console.log(arguments);return 5;})
[0, Object, 0, Array[3]]
[5, Object, 1, Array[3]]
[5, Object, 2, Array[3]]
5

MDN链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce 另一个链接:https://danmartensen.svbtle.com/javascripts-map-reduce-and-filter#reduce_1

1 个答案:

答案 0 :(得分:0)

啊,我错过了人们对初始值函数的使用,让它以数字开头而不是跳过迭代,因此不会导致第一个结果与我的例子中的数字不同。< / p>

使用较小的更改和实际结果处理示例代码:

-> [{count:1},{count:2},{count:3}].reduce(function(prev,curr){console.log(arguments);return 5;}, 0)
[0, Object, 0, Array[3]]
[5, Object, 1, Array[3]]
[5, Object, 2, Array[3]]