gpt4 book ai didi

JavaScript for 循环添加对象到对象

转载 作者:行者123 更新时间:2023-11-30 14:53:56 25 4
gpt4 key购买 nike

我有一个格式如下的数组(数据):

["1", "open_order", "form", "county", "San Diego", "title_officer", "Peter", "0"]
["2", "open_order", "form", "county", "San Diego", "branch", "MV", "0"]

当我将其通过 for 循环并将其添加到数据对象时,console.log(dataObject) 会为我提供所有条目(这就是我想要的!)然而,console.log(o) 显示最后一个条目正在进入两个记录的 o 对象。

$(function() {
var o = {};
var dataObject = {};
var i = 0;
var predata = $('#preferences').text();
var data = JSON.parse(predata);
for(i = 0; i < data.length; i++) {
dataObject['preferenceId'] = data[i][0];
dataObject['pageName'] = data[i][1];
dataObject['preferenceType'] = data[i][2];
dataObject['baseField'] = data[i][3];
dataObject['baseValue'] = data[i][4];
dataObject['targetField'] = data[i][5];
dataObject['targetValue'] = data[i][6];
dataObject['conditionalId'] = data[i][7];
o[i] = dataObject;
console.log(dataObject);
}
console.log(o);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

知道为什么 dataObject 对于添加到 o 对象的所有对象都是相同的吗?

最佳答案

您应该在循环内初始化 dataObject 以创建一个新变量。

for(i = 0; i < data.length; i++) {
var dataObject = {}; /* Init the variable here */
dataObject['preferenceId'] = data[i][0];
dataObject['pageName'] = data[i][1];
dataObject['preferenceType'] = data[i][2];
dataObject['baseField'] = data[i][3];
dataObject['baseValue'] = data[i][4];
dataObject['targetField'] = data[i][5];
dataObject['targetValue'] = data[i][6];
dataObject['conditionalId'] = data[i][7];
o[i] = dataObject;
onsole.log(dataObject);
}

这将导致:

0: {
baseField: "county",
baseValue: "San Diego",
conditionalId: "0",
pageName: "open_order",
preferenceId: "1",
preferenceType: "form",
targetField: "title_officer",
targetValue: "Peter"
}
1: {
baseField: "county",
baseValue: "San Diego",
conditionalId: "0",
pageName: "open_order",
preferenceId: "2",
preferenceType: "form",
targetField: "branch",
targetValue: "MV",
}

最终数组中的所有值都相同的原因是,您只是通过引用分配 dataObject 而不是创建新变量。

关于JavaScript for 循环添加对象到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47666601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com