2017-02-08 2 views
1

XML 파일에서 데이터를 가져 와서 JS 개체 배열에 넣으려고합니다. 여기 내 JS 코드입니다 : 내가 크롬이를 검사 할 때 올바르게 행동하는 것처럼XML 파일에서 JS 개체 배열에 데이터 추가

<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> 

, 그것은 처음에 보이는 여기

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 데이터입니다 (간결성을 위해 편집) 그러나 Object를 좀 더 자세하게 볼 때 실제로는 마지막으로 <clue>을 가져 와서 3 번 반복합니다.

Collapsed Array View

Expanded Array View (직접 때문에 평판 (10) 이하의 이미지를 게시 할 수 없습니다)

나는이 잘못된거야 어디 사람이 말해 줄래?

+0

. 나는 당신이 그것을 볼 것입니다 희망! –

답변

0

동일한 개체 (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); 
    }); 
    // ... 
} 

조언 : 그냥 코드에 대한 제안을하고자합니다. 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???) 
    }); 
}