Noobish JavaScript Nested If-Else Statement Help/Advice/Pointers/YouNameIt -
i started learning javascript (today actually) , i'd appreciate nested if-else statements. thought i'd write simple program practice, , seems every if-else statement in if blocks executes regardless of parameter put in. pointers or things notice aren't germane problem @ hand appreciated. again. code below.
edit: i've gotten now, , learned error of ways. commented , gave advice quickly.
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 2 wins!'); } else if (playertwo == 'rock' || 'rock') { alert('tie!'); } else { alert('player 1 wins!'); } } if(playerone == 'paper' || 'paper') { if (playertwo == 'paper' || 'paper') { alert('tie!'); } else if (playertwo == 'rock' || 'rock') { alert('player 1 wins!'); } else { alert('player 2 wins!'); } } if (playerone == 'scissors' || 'scissors') { if (playertwo == 'paper' || 'paper') { alert('player 1 wins!'); } else if (playertwo == 'rock' || 'rock') { alert('player 2 wins!'); } else { alert('tie!'); } } }; fight(playerone, playertwo);
as several people have pointed out, if
statements need in form of:
if (playerone == 'paper' || playerone == 'paper')
or more succinct:
if (playerone.tolowercase() == 'paper')
the problem playerone == 'paper' || 'paper'
return "truthy" value (see http://11heavens.com/falsy-and-truthy-in-javascript more detail on truthy , falsy values).
as aside, while there's absolutely nothing wrong multiple if
statements, if coding exercise way involve less if
statements (and little this:
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 unknown fist!'); } else if (fists[playerone].beats === playertwo) { alert('player 1 wins!'); } else if (fists[playertwo].beats === playerone) { alert('player 2 wins!'); } else { alert('tie!'); } }; fight(playerone, playertwo);
by objectifying rock/paper/scissors combinations, code imo easier read.
Comments
Post a Comment