这个问题在这里已有答案:
我想做一个小游戏,你必须回答一些问题。我认为最简单,最紧凑的方法是使用JavaScript对象随机提供一个问题。为此,我想要一个JavaScript对象,它在按钮点击时选择一个随机问题。但是要检查玩家是否发送了正确答案,我想要一个额外的ID来检查数据库中是否匹配的问题。
现在我的问题是:如何编码?
现在我有这个:
// Questions
var fragen = [{
frage: 'Frage 1',
id: 1
},
{
frage: 'Frage 2',
id: 2
},
{
frage: 'Frage 3',
id: 3
}
];
// Create random
var rand = fragen[Math.floor(Math.random() * fragen.length)];
// Output with question
document.getElementById("frage").innerHTML = fragen[rand];
/*Get matching ID from question to send the answer input with the matching ID
to check if the answer input is true or not */
document.getElementById("id_").value = rand;
谢谢!
rand
已经是问题对象。因此,fragen[rand]
可能未定义。相反,你可能想要访问rand.frage
和rand.id
。