我不太确定为什么 Object.assign() 没有提供预期的结果(请参见底部的注释部分)。我是否在函数中遗漏了什么,或者有更简洁的方法来实现这个功能?
下面的代码可以到达变量“i”的 for 循环,但无法到达变量“x”的第二个 for 循环。
const array_1 = [{property1:'a',property2:'b'}, {property1:'c',property2:'d'}];
const array_2 = [{property3:'w',property4:'x'}, {property3:'y',property4:'z'}];
const CombineArrays = (array_1, array_2) => {
let combined_array = [];
for (let i = 0; i < array_1.length; i++) {
for (let x = 0; x < array_2.length; x++) {
const newObj = Object.assign(array_1[i], array_2[x]);
combined_array.push(newObj);
}
}
return combined_array;
};
const result = CombineArrays(array_1, array_2);
console.log(result);
// expected result = [
// {property1:'a',property2:'b', property3:'w',property4:'x'},
// {property1:'a',property2:'b', property3:'y',property4:'z'},
// {property1:'c',property2:'d', property3:'w',property4:'x'},
// {property1:'c',property2:'d', property3:'y',property4:'z'}
// ]
// current result = [
// { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
// { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
// { property1: 'c', property2: 'd', property3: 'y', property4: 'z' },
// { property1: 'c', property2: 'd', property3: 'y', property4: 'z' }
// ]
for
循环中存在错误:for (let x = 0; x < array_2.length; x++) {
。length
属性缺失。另一个问题是您修改了array_1
的元素,而应该制作一份拷贝并分配新属性:Object.assign({}, array_1[i], array_2[x]);
。 - iY1NQObject.assign({}, array_1[i], array_2[x])
。如果不先将其复制到一个空对象中,你总是会覆盖array_1
的元素。 - iY1NQ