简体   繁体   English

为什么在这两种情况下,underscore.reduce的行为有所不同?

[英]Why does underscore.reduce acts differently in these two cases?

I was trying to flatten an object that has two objects in it, so I did the following: 我试图展平其中有两个对象的对象,所以我做了以下工作:

var underscore = require('underscore');
var obj = { a: {x:1}, b: {y:2}};
underscore.reduce(obj, underscore.extend, {});

Unexpectedly, the output that I've got was: 出乎意料的是,我得到的输出是:

{ 
   '0': 'b',
   x: 1,
   a: { x: 1 },
   b: { y: 2 },
   y: 2 
}

So then I've tried to wrap extend in a function: 因此,然后我尝试将extend包装在一个函数中:

underscore.reduce(obj, function(memo, o) {
   return underscore.extend(memo, o);
}, {});

And got the expected result: 并得到了预期的结果:

{ x: 1, y: 2 }

Why is there any difference? 为什么有什么区别? reduce expected as the 2nd argument a function that gets two arguments and returns one, and it gets it in both cases. reduce期望的作为第二个参数的函数,该函数将获取两个参数并返回一个参数,并且在两种情况下均将其获取。 So what am I missing? 那我想念什么呢?

reduce expected as the 2nd argument a function that gets two arguments and returns one... reduce期望作为第二个参数的函数,该函数将获取两个参数并返回一个参数...

Not according to the documentation . 没有根据文档 Underscore passes the iterator four , not two, arguments: 下划线传递给迭代器四个而不是两个参数:

The iterator is passed four arguments: the memo , then the value and index (or key ) of the iteration, and finally a reference to the entire list . 传递给迭代器四个参数: memo ,然后是迭代的valueindex (或key ),最后是对整个list的引用。

Consequently, you end up calling extend (on the first pass) like this: 因此,您最终会这样调用extend (在第一遍):

underscore.extend({}, {x: 1}, 'a', obj)

and then the second pass 然后第二遍

underscore.extend({/*...stuff...*/}, {y: 2}, 'b', obj)

The reason the object has a '0': 'b' attribute is that strings extend into an object containing attributes like '<index>': '<char>' . 对象具有'0': 'b'属性的原因是字符串延伸到包含'<index>': '<char>''<index>': '<char>'属性的对象中。 This is because _.extend runs a for...in... loop on each argument (except the first) and the keys found by doing that to a string are the character indexes (from 0 to str.length - 1 ). 这是因为_.extend在每个参数(第一个参数除外)上运行for...in...循环,并且通过此操作找到的键是字符索引(从0str.length - 1 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM