Havamere
Havamere

Reputation: 25

Why won't my comparison array work?

I am building a game that I want to take player inputs from prompts for, and compare them to inputs they have already used, and reject the choice if they choose the same thing twice. Here is my relevant code:

var playerChoiceRow = 0;
var playerChoiceColumn = 0;
var playerAttackArray = [];

function playerAttack(playerChoiceRow,playerChoiceColumn) {
for (var i=0; i<playerAttackArray.length; i++){
    if ([playerChoiceRow,playerChoiceColumn] === playerAttackArray[i]){
        alert("You have already attacked this space, please choose another.");
        playerChoiceRow = prompt("Please choose a number between 0 and 5.");
        playerChoiceColumn = prompt("Please choose a number between 0 and 5.");
    }
}
if (playerChoiceRow === undefined){
    alert("Please choose a number between 0 and 5!");
    playerChoiceRow = prompt("Please choose a number between 0 and 5.");
}
if (playerChoiceColumn === undefined){
    alert("Please choose a number between 0 and 5!");
    playerChoiceColumn = prompt("Please choose a number between 0 and 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 all enemy boats!");
        break;
    }
}

Upvotes: 0

Views: 50

Answers (1)

6502
6502

Reputation: 114569

In Javascript array comparison is about identity, not content; in other words === between two expressions when they're arrays returns true only if they are referring to the very same array object, not if they're two arrays containing the same things.

You could work around this problem by converting both sides to strings first:

if (""+[playerChoiceRow,playerChoiceColumn] === ""+playerAttackArray[i]) ...

Upvotes: 3

Related Questions