gpt4 book ai didi

javascript - 将 XML 文件中的数据添加到 JS 对象数组中

转载 作者:行者123 更新时间:2023-11-28 05:01:13 25 4
gpt4 key购买 nike

我正在尝试从 XML 文件中获取数据并将其推送到 JS 对象数组中。这是我的 JS 代码:

var data = [];

function parseData(xml){
console.log(xml);
var tempObj = {};
$(xml).find('question').each(function(){
data.push(tempObj);
});

$(xml).find('question').find('clue').each(function(i){
data[i]['clue'] = $(this).text();
console.log(data[i]);
});
console.log(data);
}

这是我的 XML 数据(为简洁起见进行了编辑)

<exercise>
<question>
<clue>First letter of greek alphabet</clue>
...
</question>
<question>
<clue>Second letter of greek alphabet</clue>
...
</question>
<question>
<clue>Third letter of greek alphabet</clue>
...
</question>

当我在 Chrome 中检查它时,它最初看起来表现正常,但当我更详细地查看对象时,它实际上采用了最后一个 <clue>并重复三遍。

Collapsed Array View

Expanded Array View (由于信誉低于10,无法直接发布图片)

谁能告诉我我哪里出了问题?

最佳答案

这是因为您使用的是同一个对象(tempObj 保存对同一对象的引用)。您必须为每个“question”重新定义tempObj。以下是您的代码中出现问题的示例:

var obj = {}; // declare an object ({}) and store the reference to it inside obj

obj.something = "something";

var otherObj = obj; // here you think that obj is duplicated and that obj and otherObj are two different objects but you're wrong
// obj and otherObj holds a reference to the same object.

otherObj.something = "something else";

// proof: obj.something is changed even if we didn't change it because the object it's pointing to has changed
console.log(obj);

这正是您的代码所发生的情况,数组的所有项目都指向同一个对象,因此当其中之一发生更改时,所有项目都会发生更改。

您需要为每个“question”重新定义tempObj(创建一个新对象),如下所示:

function parseData(xml){
$(xml).find('question').each(function(){
var tempObj = {}; // create a brand new object for each iteration
// fill the tempObj here
data.push(tempObj);
});
// ...
}
<小时/>

建议:只是想对您的代码提出建议。除了调用 each 两次之外,您还可以这样做:

function parseData(xml){
$(xml).find('question').each(function(){
var tempObj = {}; // create a brand new object for each iteration
data.push(tempObj);

// you could read the properies of the question here (why use another each to loop through the questions if you are already looping through the questions)
tempObj['clue'] = $(this).find('clue').text(); // even if data.push is been called before this tempObj will still changes data[i] (because of the same reference thing, got it???)
});
}

关于javascript - 将 XML 文件中的数据添加到 JS 对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42122848/

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