Simon Says游戏answerCheck函数:for循环同时输出正确与错误结果
Simon Says游戏answerCheck函数问题修复
问题根源
你的代码存在两个核心逻辑错误:
- 循环中逐个校验元素时,每匹配一个就打印"success",不匹配就打印"incorrect",只要数组里有部分匹配、部分不匹配(或者数组长度不一致导致后续索引对应
pattern元素为undefined),就会同时输出两种结果。 - 未对数组长度做前置校验,即便你说函数会在两者长度均为4时调用,但如果
pattern实际长度不符,后续索引的pattern[i]会是undefined,必然和用户输入元素不相等,触发错误分支。
修正代码
const pattern = [4, 2, 1, 3]; // 对应4长度的示例pattern function answerCheck(currentLevel) { // 前置校验长度,不一致直接判定错误 if (currentLevel.length !== pattern.length) { console.log("incorrect"); $("body").addClass("game-over"); setTimeout(() => { $("body").removeClass("game-over"); }, 300); return; } let isCorrect = true; for (let i = 0; i < currentLevel.length; i++) { if (currentLevel[i] !== pattern[i]) { isCorrect = false; break; // 发现不匹配立即终止循环,避免无效遍历 } } if (isCorrect) { console.log("success"); // setTimeout(nextSequence, 2000); // 注意不要加(),否则会立即执行函数 } else { console.log("incorrect"); // const wrong = new Audio("./sounds/wrong.mp3"); // wrong.play(); $("body").addClass("game-over"); setTimeout(() => { $("body").removeClass("game-over"); }, 300); } } answerCheck([4, 2, 1, 3]); // 测试正确输入 // answerCheck([4, 2, 3, 1]); // 测试错误输入
关键改动说明
- 增加长度校验:确保
currentLevel和pattern长度一致,避免因索引越界导致的误判。 - 统一结果判定:用
isCorrect变量标记整体匹配状态,循环中仅做校验,不直接输出结果,循环结束后根据状态一次性执行对应逻辑。 - 修正定时器写法:
setTimeout(nextSequence(), 2000)会立即执行nextSequence,改为传递函数引用setTimeout(nextSequence, 2000)才是延迟执行的正确写法。
内容的提问来源于stack exchange,提问作者jaredonnell
相关产品推荐
相关产品推荐

