【问题标题】:How to loop through instances of an Object that are pushed into an array?如何循环遍历推入数组的对象实例?
【发布时间】:2019-04-05 18:56:59
【问题描述】:

我的目标是制作一款通过随机生成向用户提出 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();

【问题讨论】:

  • 震惊的 Gretzky 不在曲棍球运动员名单中
  • 哈哈,我真的不相信那些问题和答案;)

标签: javascript


【解决方案1】:

您将希望在循环中每次都生成随机数,而不是在页面加载时生成一次。该函数循环 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);
    }
}

【讨论】:

  • 我会做
  • @ChristopherJohnston 我已经更新了。我读错了问题。
  • 有时会重复 1 个问题 2 次。你知道如何避免它这样做吗?我能以某种方式澄清这个问题吗?
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 2021-08-27
  • 2023-03-07
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 2017-02-04
  • 2016-07-28
相关资源
最近更新 更多