【问题标题】:Strange result using Array.reduce使用 Array.reduce 的奇怪结果
【发布时间】:2011-12-19 18:23:57
【问题描述】:

我正在尝试使用 jQuery.extend 函数将 JSON 对象数组合并为一个对象。 假设,我有一个示例数组:

arr = [{a:4},{b:5}];

万一:

arr.reduce( $.extend  ) 
//result { "1":{b:5}, a:4, b:5 }

但是

arr.reduce( function( a, b){ return $.extend(a,b) } );
//is ok: { a:4, b:5 }

为什么?

【问题讨论】:

    标签: javascript jquery arrays json reduce


    【解决方案1】:

    传递给reduce 的函数将接收四个参数(最后两个是当前项的索引和调用reduce 的数组)。您只对前两个感兴趣,但jQuery.extend 接受可变数量的参数,因此它会将它们全部吞掉。通过显式编写一个接受两个参数并将它们传递给extend 的函数,您可以避免这种情况并获得您期望的行为。

    【讨论】:

      【解决方案2】:

      只有在你看到reduce 实现之前,结果才看起来很奇怪,尤其是循环开始之前的这个语句:

      if(arguments.length <= 1) {  
        curr = this[0]; // Increase i to start searching the secondly defined element in the array  
        i = 1; // start accumulating at the second element  
      }  
      

      现在说得通了。而extend 本质上是动态的,所以它会接受你给它的一切(不仅仅是你真正想要的两个参数)。

      【讨论】:

      • 我不同意你的观点。如果我想将 reduce 的初始值定义为:[1,2,3].reduce(fn , init_val ) 请注意,reduce 函数总是(在我的示例中)一个参数是函数...看我的回答。
      猜你喜欢
      • 2019-04-03
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 1970-01-01
      相关资源
      最近更新 更多