gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:15:23 25 4
gpt4 key购买 nike

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

目前我只显示“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();

});
<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>

最佳答案

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

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'
}
];

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

关于javascript - 随机显示问题的名称值对的多维数组(javascript/jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com