为什么.push()方法重复添加到数组中的最后一个元素的值?

时间:2018-10-17 13:39:10

标签: javascript

const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
                {"BTCH#BD":57887,"BTYPEBD":"OCO"},
                {"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";


const result = [];
const temp = { reqId: req, batch: null };

for (var x = 0; x < maxObj.length; x++) {
    temp.batch = maxObj[x];

    result.push(temp);
}

console.log(JSON.stringify(result));

在这段代码中,我试图遍历对象数组,然后将每个对象分配给临时模板对象的属性,然后将其推送到结果数组。我的预期输出是这样的:

[{"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
 {"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
 {"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]

但是我的实际输出是这样的:

[{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}, 
 {"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}, 
 {"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]

如何解决此问题,以便在上面获得预期的输出?

1 个答案:

答案 0 :(得分:5)

您使用同一对象进行推送。您在数组内部获得了相同的对象。

您可以使用具有所需属性的新对象来防止存储相同的对象引用。

const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
            {"BTCH#BD":57887,"BTYPEBD":"OCO"},
            {"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";
const result = [];

for (var x = 0; x < maxObj.length; x++) {
    result.push({ reqId: req, batch: maxObj[x] });
}

console.log(JSON.stringify(result));