为什么我的比较数组不能工作?

Why won't my comparison array work?

本文关键字:工作 不能 数组 我的 比较 为什么      更新时间:2023-09-26

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

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

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

你可以先把两边都转换成字符串来解决这个问题:

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