与jQuery.extend合并循环:最后一个值始终是相同的吗? [英] Merge loops with jQuery.extend: last value is always the same?
问题描述
我有两个哈希"数组.我需要将它们合并在一起,所以最终结果是另一个哈希数组,但条目数是两个数组的乘积.
I have two arrays of "hashes". I need to merge them together so the end result is another array of hashes, except the number of entries is the product of the two arrays.
inhabitants = {}
idx = 0
for (i=0; i<persons.length; i++) {
person = persons[i];
for (j=0; j<houses.length; j++) {
house = houses[j];
console.log(house);
inhabitants[idx] = $.extend(person,house);
console.log(inhabitants[idx]);
idx++;
}
}
我最终得到的是一个愚蠢的条目,它取决于$ .extend()行中参数的顺序.并且添加的房屋"条目始终是阵列中的最后一个条目.
What I end up with is a silly number of entries that depends on the ordering of the parameters in the $.extend() line. And the "house" entry that is added is ALWAYS THE LAST ENTRY IN THE ARRAY.
很显然,jQuery的$ .extend()并没有达到我的期望.有人可以帮忙吗?
Clearly this $.extend() from jQuery is not doing what I expect. Can anyone help?
推荐答案
$.extend(a, b)
将b
合并到a
,然后返回a
.
$.extend(a, b)
merges b
into a
, and returns a
.
您正在使用的返回值,但似乎您错过了a
也被更改的事实-您当前每次都将相同的变量person
分配给inhabitants[idx]
.
The return value you're using but it seems you were missing the fact that a
is also being changed - you're currently assigning the same variable person
to inhabitants[idx]
each time.
这篇关于与jQuery.extend合并循环:最后一个值始终是相同的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!