[英]I have some instances of a class and I pushed them into an array. Can I loop through the array and update the price of all the array objects?
[英]How to loop through instances of an Object that are pushed into an array?
我的目标是制作一款通过随机生成向用户询问3个问题的游戏。 我通过创建一个类并创建新的问题实例并将其推入数组来解决这个问题。 之后,我做了一个函数,可以“提示”数组中的每个问题,并要求用户输入正确的答案。 如果用户输入的答案不正确,则会给用户1更多机会正确猜测答案,否则用户会松懈。
在这段代码中,我将3个问题推入问题数组,并编写了一行代码“ const randomVal = Math.floor(Math.random()* questions.length);”。 生成数组的随机元素。
我的目标是随机打印插入数组中的所有3个问题,但是我的代码仅打印1个随机问题,然后中断。
我试过在Questionz函数中使用for循环,但是我的循环没有提示3个不同的问题,而是提示了3次相同的问题。
// Creating a class
class Quiz
{
constructor(ti,opA,opB,opC,ans) // Easy
{
this.title = ti;
this.optionA = opA;
this.optionB = opB;
this.optionC = opC;
this.answer = ans;
}
}
// Making an array that will hold all the questions and options
const questions = [];
questions.push(new Quiz("Who is the greatest laker of all time?","Kobe",
"Shaq", "Magic", "Kobe"));
questions.push(new Quiz("Who is the greatest hockey player of all
time?","Crosby", "Ovechkin", "Kessel", "Crosby"));
questions.push(new Quiz("What is Torontos Baseball team called?","Blue
Jays", "Rex Sox", "Yankees", "Blue Jays"));
const randomVal = Math.floor(Math.random() * questions.length);
let que1; // This is global
let i=0;
function Questionz() // Easy Questions (lvl 1)
{
que1 = prompt(`Q. ${questions[randomVal].title}
\n\n1.${questions[randomVal].optionA}
\n2.${questions[randomVal].optionB}\n3.${questions[randomVal].optionC}`);
Validation(randomVal);
}
// BOTTOM FUNCTION GIVES PROMPTED VALUE VALIDATION
function Validation(randomVal)
{
while(que1 !== questions[randomVal].answer)
{
que1 = prompt(`${que1} is Incorrect!\n\nPlease try again!`);
i++;
if(que1 === questions[randomVal].answer)
{
alert("Correct!\n\nPress OK to move onto the next question!");
}
else if(i===1)
{
alert(`${que1} is incorrect.\n\nYou have lost.`);
break;
}
}
}
Questionz();
您将要在循环中每次生成一次随机数,而不是页面加载一次。 此函数循环3次并创建3个随机数。
function Questionz() // Easy Questions (lvl 1)
{
for(let z = 0; z < questions.length; z++) {
let randomVal = Math.floor(Math.random() * questions.length);
que1 = prompt(`Q. ${questions[randomVal].title}
\n\n1.${questions[randomVal].optionA}
\n2.${questions[randomVal].optionB}\n3.${questions[randomVal].optionC}`);
Validation(randomVal);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.