为什么这个数组的最后一个元素被拼接而不是中间的一个?

Why is the last element of this array being spliced instead of a middle one?

出于某种原因,当尝试从数组 enemies 中拼接中间索引时,最后一个元素被删除了。我问过几个人,但他们不知道问题出在哪里。

如果我向第 5 个敌人射击,则拼接数组的最后一个元素而不是索引 5。

enemies.forEach(function(element, index){
    for(var i = 0; i < bullets.length; i++) {
        if(bullets[i].X + 5 > element.X && bullets[i].X < element.X+30 && 
            bullets[i].Y + 5 > element.Y && bullets[i].Y < element.Y+30){
            //These conditions look messy but they work

            console.log(index); //This Outputs the Correct Index
            enemies.splice(index, 1); //<- Splices The Last Index instead of a specific one

            bullets.splice(i, 1); 
        }
    }
})

这个 Link 有我的整个代码的副本和这个函数的替代版本 https://pastebin.com/Q7swAh1a

  1. 为什么没有拼接正确的索引?
  2. 如何修改这段代码才能拼接正确的索引?

您的问题在这里:

for(var i = 0; i < enemies.length; i++) {
    enemies[i].Draw((66*i)+18, 50, i);//Here is the bug
    enemies[i].Move();
}

这里

this.Draw = function(x, y, i) {
    this.X = x;//These 2 lines overwrite the real positions
    this.Y = y;

    ctx.fillStyle = 'orange';
    ctx.fillRect(this.X, this.Y, 30, 30);
    ctx.fillStyle = 'white';
    ctx.fillText(i, this.X, this.Y);
}

你根据他们在数组中的索引而不是他们自己的位置来绘制你的敌人。

这应该有效:

for(var i = 0; i < enemies.length; i++) {
    enemies[i].Draw(i);
    enemies[i].Move();
}

this.Draw = function(i) {

    ctx.fillStyle = 'orange';
    ctx.fillRect(this.X, this.Y, 30, 30);
    ctx.fillStyle = 'white';
    ctx.fillText(i, this.X, this.Y);//i would be the index in the array and changes with splice()
}