为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

跃然一笑 2021-11-12 16:19:01
    这是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>    <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!") 并且程序将停止运行。我在三元运算符的帮助下做到了这一点。但是,为什么我的程序会一直运行?
查看完整描述

1 回答

?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

checkAnswer总是返回 undefined 因为你没有做return任何事情:


Question.prototype.checkAnswer=function(answer) {

  return answer==this.correct

}


查看完整回答
反对 回复 2021-11-12
  • 1 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信