gpt4 book ai didi

javascript - 即使我正确填写了提示(),我的 if 语句怎么会不起作用

转载 作者:行者123 更新时间:2023-11-28 12:59:28 24 4
gpt4 key购买 nike

所以我正在制作一个石头、剪刀、布的小游戏,你可以在其中与电脑进行对抗。

但是,我做了一个 if 语句来检查您是否填写了“石头、剪刀、布”。如果没有,它应该返回一个 alert() ,表明您没有填写这 3 个中的一个,但是当我填写石头、布或剪刀时,它仍然返回 alert().

功能:

function rockPaperScissors() {
let computerChoice;
let loopFunction = false;
let draw = 0;

while (loopFunction === false) {
let playerGuess = prompt('Enter rock, paper or scissors!');
let computerChoiceCalculator = Math.floor(Math.random() * 10);

if (playerGuess == '') {
window.alert('ggggg');
return;
} else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}
else {
if (computerChoiceCalculator <= 4) {
computerChoice = 'rock';
console.log(computerChoice);
} else if (computerChoiceCalculator <= 7) {
computerChoice = 'paper';
console.log(computerChoice);
} else {
computerChoice = 'scissors';
console.log(computerChoice);
}

if (playerGuess === computerChoice) {
draw += 1;
window.alert('THIS WAS A DRAW! THE COMPUTER HAD ' + computerChoice + ' AND U HAD ' + playerGuess);
} else if (playerGuess === 'rock' && computerChoice === 'paper' || playerGuess === 'paper' && computerChoice === 'scissors' || playerGuess === 'scissors' && computerChoice === 'rock') {
window.alert('The computer won this round! Lets try again! your try was ' + playerGuess + ' and the computer had ' + computerChoice);
} else {
window.alert('fuck yeah! u won!');
}
}
}
}

导致问题的代码:

else if (playerGuess != 'rock' || 'paper' || 'scissors') {
window.alert('Please enter rock, paper or scissors');
}

最佳答案

哦,这是错误的:

else if (playerGuess != 'rock' || 'paper' || 'scissors')

此条件不起作用,因为您无法像这样对相等运算符进行分组。

您必须对每个项目进行比较。正如所写的,这个条件将始终返回 true,因为 'paper' 将始终是一个真值。

你应该这样做:

else if (playerGuess != 'rock' && playerGuess != 'paper' && playerGuess != 'scissors')

或者你可以这样做,这样更漂亮:

else if (!['rock', 'paper', 'scissors'].includes(playerGuess))

关于javascript - 即使我正确填写了提示(),我的 if 语句怎么会不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52184334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com