gpt4 book ai didi

javascript - Noobish JavaScript 嵌套 If-Else 语句帮助/建议/指针/YouNameIt

转载 作者:行者123 更新时间:2023-11-28 20:25:46 25 4
gpt4 key购买 nike

我刚刚开始学习 JavaScript(实际上是今天),我非常感谢有关嵌套 if-else 语句的一些帮助。我想我应该编写一个简单的程序来练习,似乎 if block 中的每个 if-else 语句都会执行,无论我输入哪个参数。任何指针甚至您注意到与问题无关的东西手受到赞赏。再次感谢。我的代码如下。

编辑:我现在已经明白了,并且认识到了我的方式的错误。感谢所有如此迅速发表评论和提供建议的人。

var playerOne = prompt('Choose rock, paper, or scissors'); 
var playerTwo = prompt('Choose rock, paper, or scissors');

var fight = function (playerOne, playerTwo)
{
if( playerOne == 'rock' || 'Rock')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Player Two Wins!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Tie!');
}
else
{
alert('Player One wins!');
}
}

if(playerOne == 'paper' || 'Paper')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Tie!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Player One Wins!');
}
else
{
alert('Player Two wins!');
}
}

if (playerOne == 'scissors' || 'Scissors')
{
if (playerTwo == 'paper' || 'Paper')
{
alert('Player One Wins!');
}
else if (playerTwo == 'rock' || 'Rock')
{
alert('Player Two Wins!');
}
else
{
alert('Tie!');
}
}

};

fight(playerOne, playerTwo);

最佳答案

正如一些人指出的那样,您的 if 语句需要采用以下形式:

if (playerOne == 'paper' || playerOne == 'Paper')

或者更简洁:

if (playerOne.toLowerCase() == 'paper')

问题是 playerOne == 'paper' || “Paper” 将始终返回“Truthy”值(有关 Truthy 和 Falsy 值的更多详细信息,请参阅 http://11heavens.com/falsy-and-truthy-in-javascript)。

顺便说一句,虽然多个 if 语句绝对没有任何问题,但如果我编写这个练习,我的方式将涉及更少的 if 语句(看起来有点像这个:

var playerOne = prompt('Choose rock, paper, or scissors');
var playerTwo = prompt('Choose rock, paper, or scissors');
var fists = {
"rock": {
"beats": "scissors",
"loses": "paper"
},
"paper": {
"beats": "rock",
"loses": "scissors"
},
"scissors": {
"beats": "paper",
"loses": "rock"
}
}

var fight = function (playerOne, playerTwo) {
playerOne = playerOne.toLowerCase();
playerTwo = playerTwo.toLowerCase();

if (fists[playerOne] === undefined || fists[playerTwo] === undefined) {
alert('Someone threw an unknown fist!');
} else if (fists[playerOne].beats === playerTwo) {
alert('Player One wins!');
} else if (fists[playerTwo].beats === playerOne) {
alert('Player Two Wins!');
} else {
alert('Tie!');
}
};

fight(playerOne, playerTwo);

通过具体化石头/剪刀/布的组合,在我看来代码更容易阅读。

关于javascript - Noobish JavaScript 嵌套 If-Else 语句帮助/建议/指针/YouNameIt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453896/

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