JavaScript中else if使用问题:console.log未输出对应结果
问题:石头剪刀布游戏胜负判断逻辑失效
原始代码
// Array for game options (*added the array as requested*) const picks = ["Lapis", "Papyrus", "Scalpellus"]; // Computer's new pick const compNewChoice = Math.floor(Math.random() * 3); console.log("Computer chose " + picks[compNewChoice]); // Player's new pick const playerNewChoice = Math.floor(Math.random() * picks.length); console.log("Player chose " + picks[playerNewChoice]); if (compNewChoice === picks[0]) { if (playerNewChoice === picks[1]) { console.log("Computer chose " + picks[0] + " and Player chose " + picks[1] + " Player Wins!"); } else if (playerNewChoice === picks[2]) { console.log("Computer chose " + picks[0] + " and Player chose " + picks[2] + " Computer Wins!"); } else { console.log(" It's a Draw! Computer chose " + picks[0] + " and Player chose " + picks[0]); } }
问题现象
当电脑选择picks[0]且玩家选择picks[2]时,仅输出:
"Computer chose Lapis"
"Player chose Scalpellus"
未输出预期的胜负结果:"Computer chose Lapis and Player chose Scalpellus Computer Wins!"
尝试修改后的代码
if (compNewChoice === playerNewChoice) { console.log("It's a Draw"); } if (compNewChoice === picks[0]) { if (playerNewChoice === picks[1]) { console.log("Computer chose " + picks[0] + " and Player chose " + picks[1] + " Player Wins!"); } else if (playerNewChoice === picks[2]) { console.log("Computer chose " + picks[0] + " and Player chose " + picks[2] + " Computer Wins!"); } }
此时平局判断正常,但胜负判断仍然失效。
问题根源与解决方案
核心错误是把数组索引和数组元素值混淆:
compNewChoice和playerNewChoice是随机生成的数字索引(0、1、2),但代码里却拿它们和picks[0]、picks[1]这类字符串元素做比较,两者类型、值均不匹配,导致条件永远无法触发。
修正方法:将条件判断中的元素值替换为对应索引:
const picks = ["Lapis", "Papyrus", "Scalpellus"]; // Computer's new pick const compNewChoice = Math.floor(Math.random() * 3); console.log("Computer chose " + picks[compNewChoice]); // Player's new pick const playerNewChoice = Math.floor(Math.random() * picks.length); console.log("Player chose " + picks[playerNewChoice]); // 先判断平局 if (compNewChoice === playerNewChoice) { console.log(`It's a Draw! Computer chose ${picks[compNewChoice]} and Player chose ${picks[playerNewChoice]}`); } // 电脑选Lapis(索引0)的胜负判断 else if (compNewChoice === 0) { if (playerNewChoice === 1) { console.log(`Computer chose ${picks[0]} and Player chose ${picks[1]} Player Wins!`); } else if (playerNewChoice === 2) { console.log(`Computer chose ${picks[0]} and Player chose ${picks[2]} Computer Wins!`); } } // 可继续补充电脑选其他选项的判断逻辑
另外,推荐使用模板字符串(` `)拼接内容,比+运算符更清晰易读。
内容的提问来源于stack exchange,提问作者tre3
相关产品推荐
相关产品推荐

