【发布时间】:2019-12-29 19:47:02
【问题描述】:
我正在通过 The Odin 项目学习 JavaScript,目前坚持使用石头剪刀布练习。下面的程序在单轮中正常运行,但是当我向 game() 函数添加 for 循环 以调用 playRound() 五次时并保持分数它会为 for 循环 所在的行提供 无限循环错误。
程序可以进行不同的配置,但这是项目要求的。任何帮助表示赞赏。
//random choice generator
function computerPlay() {
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
let number = getRandomArbitrary(0, 3)
if (number == 0) {
return 'ROCK'
} else if (number == 1) {
return 'PAPER'
} else {
return 'SCISSORS'
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Single Round Main
function playRound(playerSelection, computerSelection) {
playerSelection = playerSelection.toUpperCase()
if (computerSelection == playerSelection) {
console.log('DEUCE')
return 0
} else if ((playerSelection == 'ROCK' && computerSelection == 'SCISSORS') || (playerSelection == 'PAPER' &&
computerSelection == 'ROCK') || (playerSelection == 'SCISSORS' && computerSelection == 'PAPER')) {
console.log('You Win! ' + playerSelection + ' beats ' + computerSelection + '.')
return 1
} else if ((playerSelection == 'SCISSORS' && computerSelection == 'ROCK') || (playerSelection == 'ROCK' &&
computerSelection == 'PAPER') || (playerSelection == 'PAPER' && computerSelection == 'SCISSORS')) {
console.log('You Lose! ' + computerSelection + ' beats ' + playerSelection + '.')
return 0
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
function game() {
let score = 0
for (i = 0; i < 5; i++) {
let computerSelection = computerPlay()
let playerSelection = prompt('Choose one! Rock, Paper or Scissors.')
let result = playRound(playerSelection, computerSelection)
if (result == 1) {
score += 1
} else {
score += 0
}
}
console.log(score)
}
game()
【问题讨论】:
-
您应该在 for 循环中定义变量 -
for (let i = 0; .... -
你能添加你如何玩 5 个游戏的代码吗?
-
对我来说运行良好(在 chrome 版本 79.0.3945.88 中)
-
I posted a question about this。似乎由于某种原因,有一个模态对话框被检测为“潜在的无限循环”。发生在 JSBin 上,但我猜您使用的平台要么采用相同的算法来分析代码,要么实际上可能正在使用 JSBin 来执行。无论如何,我不知道为什么这被检测为“可能无限”。要么是错误,要么存在实际问题。
-
所以,结果分析比我想象的要简单得多。循环只需要“太多时间”。在 JSBin 上,如果超过 100 毫秒,循环将被终止。并且由于
prompt将等待用户输入并且它需要比超时时间更长的时间,它被错误地检测为“可能无限”。
标签: javascript function infinite-loop