为什么我的比较阵列不起作用?

时间:2015-08-30 16:35:50

标签: javascript

我正在构建一个游戏,我想从提示中获取玩家输入,并将它们与已经使用的输入进行比较,如果他们选择相同的两次,则拒绝选择。这是我的相关代码:

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;
    }
}

1 个答案:

答案 0 :(得分:3)

在Javascript数组中,比较是关于身份,而不是内容;换句话说,两个表达式之间的===当它们是数组时,只有当它们引用同一个数组对象时才返回true,而不是它们是两个包含相同内容的数组。

您可以先将双方转换为字符串来解决此问题:

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