javascript - Why won't my comparison array work? -
i building game want take player inputs prompts for, , compare them inputs have used, , reject choice if choose same thing twice. here relevant code:
var playerchoicerow = 0; var playerchoicecolumn = 0; var playerattackarray = []; function playerattack(playerchoicerow,playerchoicecolumn) { (var i=0; i<playerattackarray.length; i++){ if ([playerchoicerow,playerchoicecolumn] === playerattackarray[i]){ alert("you have attacked space, please choose another."); playerchoicerow = prompt("please choose number between 0 , 5."); playerchoicecolumn = prompt("please choose number between 0 , 5."); } } if (playerchoicerow === undefined){ alert("please choose number between 0 , 5!"); playerchoicerow = prompt("please choose number between 0 , 5."); } if (playerchoicecolumn === undefined){ alert("please choose number between 0 , 5!"); playerchoicecolumn = prompt("please choose number between 0 , 5."); } playerattackarray.push([playerchoicerow,playerchoicecolumn]); while (playercounter || computercounter <=4){ var playerchoicerow = prompt("please select row of attack. (0 though 5)")-''; var playerchoicecolumn = prompt("please select column of attack. (0 though 5)")-''; playerattack(playerchoicerow,playerchoicecolumn); if (playercounter == 5){ alert("you have sunk enemy boats!"); break; } }
in javascript array comparison identity, not content; in other words ===
between 2 expressions when they're arrays returns true if referring same array object, not if they're 2 arrays containing same things.
you work around problem converting both sides strings first:
if (""+[playerchoicerow,playerchoicecolumn] === ""+playerattackarray[i]) ...
Comments
Post a Comment