2017-03-27 20 views
0

我想写脚本,将显示随机问题。我无法弄清楚如何做到这一点。在javascript中的随机对象

这是我不工作(=不写元素上的任何东西)代码:

function theQ(quest, ans) { // question constructor 
    this.question = quest; 
    this.answer = ans; 
} 
var quest1 = new theQ("1+1", "2"); // object 1 
var quest2 = new theQ("2+2", "4"); // object 2 
var container = document.getElementById("rendomQuestion"); // display 
var randomNumber = Math.random(); // randomize 
var numQuestion = Math.floor(randomNumber * theQ.length); // between theQ number of objects 
container.innerHTML += quest+numQuestion.question; // write the chosen question. 

请告诉我,我到底做错了..

编辑 - 这是我的HTML :

<p id="rendomQuestion"></p> 
+3

请定义“不工作”?你会得到什么错误?发布您的HTML以及。我们需要一个[mcve] – j08691

+0

这是一个可怕的重复(它是http://stackoverflow.com/q/5117127/251311)。对不起社区,但删除它,因为它完全不相关 – zerkms

+0

@epascarello,除非它不是OP所需的。 OP不需要变量变量,但有助于在两者之间选择一个值。 – zerkms

回答

2

您应该使用数组(两个问题):

function theQ(quest, ans) { // question constructor 
 
    this.question = quest; 
 
    this.answer = ans; 
 
} 
 
// *** Make it an array: 
 
var quests = [new theQ("1+1", "2"), 
 
       new theQ("2+2", "4")]; 
 
var container = document.getElementById("rendomQuestion"); 
 
var randomNumber = Math.random(); 
 
var numQuestion = Math.floor(randomNumber * theQ.length); 
 
// *** Now use array notation: 
 
container.textContent = quests[numQuestion].question;
<p id="rendomQuestion"></p>

+0

为什么这是低调? – zerkms

+0

工作就像一个魅力。我尝试使用对象为了检查用户答案是否正确。谢谢。 –

+0

@trincot如果你可以看看这个http://stackoverflow.com/questions/43086730/create-random-arrays-in-javascript –