這是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!") 并且程序?qū)⑼V惯\行。我在三元運算符的幫助下做到了這一點。但是,為什么我的程序會一直運行?
實現(xiàn)三元運算符創(chuàng)建無限循環(huán)
躍然一笑
2021-11-12 16:19:01