简体   繁体   English

JavaScript Battleship阵列接头

[英]JavaScript Battleship Array splice

I'm making a battleship game in JavaScript and I stumbled upon a problem 我正在用JavaScript制作战舰游戏,却偶然发现一个问题

    var targetString = target.replace(/\s+/g, '');
    for(var i = 0; i !== inputArray.length; i++) {
        for(var j = 0; j !== boats[i].usedPositions.length; j++) {
            if(targetString === boats[i].usedPositions[j].toString()) {
                hit = true;
                boats[i].hits[j] = 1;
                console.log(boats[i].hits);
                currentBoat = boats[i];
                boats[i].usedPositions.splice(j,1);
                break;
            }                                
        }  
    }

    if(hit && stop == false) {
        alert ("Hit!");
        if(allEquals(currentBoat.hits, 1) && hit) {
            alert("Boat with length " + currentBoat.hits.length + " has sunken!");
            sunkenBoat++;
        }
    }

The first piece of code checks if the entered coordinate matches a coordinate of the boats (all of these are stored in usedPositions). 第一段代码检查输入的坐标是否与船的坐标匹配(所有这些都存储在usedPositions中)。 To prevent that the player can hit that boat again, I want to take the hit coordiante out of that array using splice. 为了防止玩家再次击中该船,我想使用拼接将击中的coordiante从该阵列中取出。 But when I do this, it doesn't alert me when a boat has sunken (second piece of code). 但是,当我这样做时,它不会在船下沉时提醒我(第二段代码)。 When the line with splice in is removed, it does give the alert. 删除带有接头的线时,它会发出警报。 Can anyone help me? 谁能帮我? Full code is found here . 完整的代码可以在这里找到。

splice moves the subsequent array elements down to fill the space. splice将随后的数组元素向下移动以填充空间。 Your logic doesn't look like it's expecting things to move like that. 您的逻辑看起来并不像预期的那样。

Instead of splice , you probably just want to assign some other value to that array location, eg: 除了splice ,您可能只想向该数组位置分配其他值,例如:

boats[i].usedPositions[j] = " "; // Where " " is assumed not to represent a boat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM