我正在尝试从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>
并重复三次次。
Expanded Array View(由于声誉低于10,无法直接发布图片)
有谁能告诉我这个问题出在哪里?
答案 0 :(得分:0)
这是因为您正在使用相同的对象(tempObj
保存对同一对象的引用)。您必须为每tempObj
次重新定义"question"
。以下是代码中出现问题的示例:
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);
&#13;
正是你的代码发生了什么,数组的所有项都指向同一个对象,所以当其中一个被更改时,所有这些都会被更改。
您需要为每个tempObj
重新定义"question"
(创建一个新对象),如下所示:
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);
});
// ...
}
建议:只想对您的代码提出建议。 Insead两次调用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???)
});
}