总体而言,我对编程还很陌生,所以这可能是一个非常基本的问题。
英语也不是我的母语,如果我不太擅长表达自己的话,我会很喜欢。
const questions = [{
question: "what is 2 + 2 ?",
answer: [{
text: "4",
correct: true
}];
]
function showQuestion(question) {
questionElement.innerText = question.question
}
我无法理解,我们如何在不调用对象object.property(questions.question)
而是使用parameter.property(question.question)
的情况下访问对象问题的问题属性(“ 2 + 2是什么?”)?
答案 0 :(得分:1)
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)
答案 1 :(得分:0)
questions
是一个数组,大概包含多个对象,如您显示的那样。
您可以这样调用函数:
var i = Math.floor(Math.random() * questions.length); // Get random array index
showQuestion(questions[i]);
执行此操作时,所选数组元素将成为函数中question
的值。然后,您可以使用question.propertyname
访问其属性。
如果您仍然不了解,则需要复习学习资料,其中介绍了函数调用的部分。
答案 2 :(得分:0)
您可以使用的另一种方法是对象解构和数组解构的混合,以访问对象和数组属性,而无需显式指定索引或使用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}`);