为什么我的比较数组不能工作?
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,而不是当它们是包含相同内容的两个数组时。
你可以先把两边都转换成字符串来解决这个问题:
if (""+[playerChoiceRow,playerChoiceColumn] === ""+playerAttackArray[i]) ...
相关文章:
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- JS可以在Chrome中工作,但不能在Firefox中工作
- javascript扫雷器floodfill算法不能正常工作
- JavaScript指令不能像我想象的那样工作
- Facebook登录按钮没有'不能在Firefox上工作
- jQuery Datepicker可以在Safari中工作,但不能在FF或Chrome中工作
- javascript没有´我不能在joomla 3.0中工作
- 用javascript将script元素附加到头部;铬不能工作
- jQuery函数不能只在一个页面上工作
- 为什么这个代码不能正常工作
- 为什么jquery悬停在jsfiddle中可以工作,而在我的html布局中却不能
- 为什么我的JavaScript在Safari上的严格模式下不能正常工作
- 为什么Turbolinks不能正常工作?Rails应用程序
- jQuery dosn'内联函数不能按预期工作
- 为什么这个javascript工作不能正确地分配.cells[] ?
- 谷歌应用引擎云端点:OAuth2不工作.不能加载api
- 输入焦点不工作/不能选择单选按钮-引导
- LocalStorage不能在iPhone上工作-不能在私人浏览
- 工作不能代替生活