[英]How do we access the property of the object without calling object.property?
一般來說,我對編程很陌生,所以這可能是一個非常基本的問題。
英語也不是我的母語,如果我不能很好地表達自己,我很抱歉。
const questions = [{
question: "what is 2 + 2 ?",
answer: [{
text: "4",
correct: true
}];
]
function showQuestion(question) {
questionElement.innerText = question.question
}
我無法理解,我們如何訪問對象問題的 question 屬性(“什么是 2 + 2 ?”)而不調用它的object.property(questions.question)
而是使用parameter.property(question.question)
?
const questions = [{ question: "what is 2 + 2 ?", answer: [{ text: "4", correct: true }] }, { question: "what is 8 + 2 ?", answer: [{ text: "10", correct: true }] }, { question: "what is 8 - 4 ?", answer: [{ text: "4", correct: true }] } ] function showQuestion(id) { // questionElement.innerText = question.question console.log('question:'+ questions[id].question) } var id = Math.floor(Math.random() * questions.length) showQuestion(id)
questions
是一個數組,大概包含多個對象,如您展示的對象。 你這樣調用函數:
var i = Math.floor(Math.random() * questions.length); // Get random array index
showQuestion(questions[i]);
執行此操作時,所選數組元素將成為函數中的question
值。 然后,您可以使用question.propertyname
訪問其屬性。
如果你還是不明白,你需要復習一下你的學習資料,解釋函數調用的部分。
您可以使用的另一種方法是混合使用對象解構和數組解構來訪問對象和數組屬性,而無需明確指定索引或使用obj.prop
。 例如:
const questions = [{ question: "what is 2 + 2 ?", answer: [{ text: "4", correct: true }] }]; const [{ question, answer }] = questions; const [{ text, correct }] = answer; console.log(`${question}: ${text}`);
您可以將問題ID傳遞給以下功能,然后您可以找到問題並在需要時回答我目前正在傳遞隨機ID
const questions = [{ question: "what is 2 + 2 ?", answer: [{ text: "4", correct: true }] }, { question: "what is 8 + 2 ?", answer: [{ text: "10", correct: true }] }, { question: "what is 8 - 4 ?", answer: [{ text: "4", correct: true }] } ] function showQuestion(id) { // questionElement.innerText = question.question console.log('question:'+ questions[id].question) } var id = Math.floor(Math.random() * questions.length) showQuestion(id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.