如何修复颜色猜选游戏中只有第一个alert弹窗生效的问题
问题根因
- 函数调用名与实际定义名不匹配:代码中定义的校验函数名为
checkGuessing,但runGame内调用的是不存在的checkGuess,触发未定义引用报错,直接中断后续代码执行 - 校验函数调用逻辑错误:
checkGuess的调用被放在return语句之后,永远无法执行;且仅在用户点击prompt取消按钮(guess === null)时才尝试调用,正常输入场景下完全不会触发校验,correct变量永远保持初始的false值 - 校验函数内部判断逻辑完全写反:
COLOR_ARRAY.includes(guess)为true代表输入的是合法颜色,现有逻辑会在输入合法时提示「颜色不识别」 - 校验函数返回值逻辑错误:不管用户输入是否正确,永远返回固定的
true,无法正确传递校验结果 - 合法输入场景下未修改
correct变量值,导致do-while循环条件永远满足,无法正常退出
修正后的完整代码
const COLOR_ARRAY = ['blue', 'cyan', 'gold', 'gray', 'green', 'magenta', 'orange', 'red', 'white', 'yellow']; function runGame() { let guess = ""; let correct = false; const targetIndex = Math.floor(Math.random() * COLOR_ARRAY.length); const target = COLOR_ARRAY[targetIndex]; console.log('正确答案:', targetIndex, target); do { guess = prompt('I am thinking of one of these colors:\n\n' + COLOR_ARRAY + '\n\n What color am I thinking of ?\n'); if (guess === null) { alert('bye'); return; } // 正常输入场景下调用校验函数 correct = checkGuessing(guess, target); } while (!correct); alert('congratulations!'); } function checkGuessing(guess, target) { // 先判断输入是否合法 if (!COLOR_ARRAY.includes(guess)) { alert('Color not recognized.'); return false; } // 按字典序比较猜的颜色和目标 if (guess > target) { alert('Guess incorrect\n\n higher than target.'); return false; } else if (guess < target) { alert('Guess is incorrect...Lower than target.'); return false; } // 完全匹配返回正确 return true; } runGame();
关键修改说明
- 统一校验函数调用名和定义名,消除未定义报错
- 将校验函数调用移到
guess === null判断分支外,保证所有正常输入都会执行校验 - 修正合法性判断的逻辑,仅当输入不在颜色数组内时提示不识别
- 调整校验函数返回值:输入非法、猜高、猜低都返回
false,完全匹配才返回true - 删除无用变量,简化校验逻辑
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

