名称值的多维数组随机显示问题(javascript/jquery)

Nic*_*989 0 javascript arrays jquery

我是多维数组的新手,并使用这样的对象来显示数据.我想要实现的是循环并在数组中随机显示一个问题,然后用户将输入"更高或更低"的答案,并将输入值与答案对象相匹配.

目前我只是显示"0"作为我的输出.我假设这与questions.length部分只是一个数组,因为开始括号由对象组成?

如何实现随机问题生成?

如果我需要进一步解释请告诉我,但它应该只是一个简单的问题,并将用户输入的值与答案进行比较,并显示正确或不正确.

$(function() {

function gameStart(){	
	var questions = [
		{	 
			question1: {
				question: 'Is the price higher or lower than $40.00?', 
				answer: 'higher'
			},
			question2: {
				question: 'Is the price higher or lower than $100.00?', 
				answer: 'higher'
			},
			question3: {
				question: 'Is the price higher or lower than $50.00?', 
				answer: 'lower'
			}
		}
	];

	var i;
	for(i = 0; i < questions.length; i++) {
		document.getElementById("question").innerHTML = Math.floor(Math.random()*questions.length);
	}
}
gameStart();

});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h2 id="question"></h2>
</div>
	<label for="text">Answer:</label>
	<input id="user-answer" type="text" value="">
	<button id="submit" type="submit">Submit</button>

	<p id="sorry" style="display: none">Sorry...</p>
	<p id="correct" style="display: none">You got it!</p>
Run Code Online (Sandbox Code Playgroud)

小智 5

首先,我会改变你的对象结构:

var questions = [
    {
        question: 'Is the price higher or lower than $40.00?', 
        answer: 'higher'
    },
    {
        question: 'Is the price higher or lower than $100.00?', 
        answer: 'higher'
    },
     {
        question: 'Is the price higher or lower than $50.00?', 
        answer: 'lower'
    }
];
Run Code Online (Sandbox Code Playgroud)

更改为此结构后,您将能够使用以前的代码访问问题:var index = Math.floor(Math.random()*questions.length).这将返回您的问题的索引.现在您可以访问对象,如:questions[index].questionquestion[index].answer.