2016-02-23 50 views
-1

如何迭代每個科學對象/數組的第一個元素(問題)?我使用「science.question」,這是行不通的。 ```如何選擇對象中的數組的第一個孩子?

var scienceQuestion = { 
    scienceQue: function(){ 
    for (var i = 0; i <science.question.length; i++) 
    science.question = questionsDiv.innerHtml 
    }, 
science: [ 
    { question: "What size is", 
    choices: [10,44,15], 
    correctIndex: 1 
    }, 

    { question: "???", 
    choices: [0,1,2], 
    correctIndex: 2 
    } 

] 
} 

```

回答

0

我希望你的代碼看起來更象這樣......

var scienceQuestion = { 
scienceQue: function() { 
    for (var i = 0; i < this.science.length; i++) { 
     questionsDiv.innerHTML += this.science[i].question; 
    } 
}, 
science: [ 
    { question: "What size is", choices: [10, 44, 15], correctIndex: 1 }, 
    { question: "???", choices: [0, 1, 2], correctIndex: 2 } 
] 
} 

您已經定義了scienceQuestion對象的方式,科學它的一個屬性,是一個數組。因此,您需要在scienceQuestion對象中使用它來引用它,例如this.science。因爲它是一個數組,所以你需要使用this.science [0]等來引用數組的元素。如果需要迭代它們,則使用for循環並使用this.science [i]將循環中的每個元素都設置爲this.science.length,如上所示。我的示例僅附加到div元素的innerHTML屬性,以便您可以看到結果。希望有所幫助:)

相關問題