【问题标题】:Why in JavaScript does the array reduce function change parameters after the first iteration?为什么在 JavaScript 中数组会在第一次迭代后减少函数更改参数?
【发布时间】:2016-08-01 02:09:49
【问题描述】:

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

> [{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

【问题讨论】:

    标签: javascript parameters parameter-passing reduce


    【解决方案1】:

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

    变化很小的工作示例代码和实际结果:

    -> [{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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      相关资源
      最近更新 更多