实现三元运算符会创建无限循环

问题描述 投票:0回答:1

这是JS:

function Question(question, answers, correct) {
  this.question=question;
  this.answers=answers;
  this.correct=correct;
}

Question.prototype.displayQuestion=function () {
  console.log(this.question)
  this.answers.forEach((answer, i)=> {
    console.log(`${i}: ${answer}`)
  })
}

Question.prototype.checkAnswer=function(answer) {
  (answer==this.correct)? true: false
}


var q1=new Question("What day is it today?", ["Monday", "Tuesday"], 0)
var q2=new Question("How are you?", ["Good", "Really good"], 1)
var q3=new Question("Is it nice out?", ["Yes", "No", "In-between"], 3)
var questions=[q1, q2, q3];

function createGame() {
  var num=Math.floor(Math.random()*questions.length)
  questions[num].displayQuestion()
  var userInput=parseInt(prompt("Please enter answer"))
  questions[num].checkAnswer(userInput)? console.log('You won!'): createGame()
}

createGame()

这是index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Section 5: Advanced JavaScript: Objects and Functions</title>
    </head>

    <body>
        <h1>Section 5: Advanced JavaScript: Objects and Functions</h1>
        <script src="script.js"></script>
    </body>
</html

我使用这个简单程序的目标是一直输出问题,直到用户正确为止。如果用户正确解决了该问题,则可以使用console.log(“ You won!”),该程序将停止运行。我是在三元运算符的帮助下完成的。但是,为什么我的程序会永远运行?

javascript ternary-operator infinite
1个回答
0
投票

[checkAnswer总是返回未定义,因为您没有return-进行任何操作:

Question.prototype.checkAnswer=function(answer) {
  return answer==this.correct
}
© www.soinside.com 2019 - 2024. All rights reserved.