[英]Why won't my comparison array work?
我正在构建一个游戏,我希望从提示中获取玩家的输入,并将其与他们已经使用的输入进行比较,如果他们两次选择相同的内容,则拒绝选择。 这是我的相关代码:
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,而不是两个包含相同事物的数组时才返回true。
您可以通过首先将两面都转换为字符串来解决此问题:
if (""+[playerChoiceRow,playerChoiceColumn] === ""+playerAttackArray[i]) ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.