首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么这个数组的最后一个元素被拼接,而不是中间一个呢?

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

Stack Overflow用户
提问于 2018-03-18 18:30:44
回答 1查看 54关注 0票数 0

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

如果我向第五个敌人发射子弹,数组的最后一个元素就会被拼接,而不是索引5。

代码语言:javascript
复制
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); 
        }
    }
})

这个链接有我的全部代码的副本和这个函数https://pastebin.com/Q7swAh1a的备用版本。

  1. 为什么正确的索引没有拼接?
  2. 如何修复此代码以使正确的索引被拼接?
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-18 18:48:10

你的问题是:

代码语言:javascript
复制
for(var i = 0; i < enemies.length; i++) {
    enemies[i].Draw((66*i)+18, 50, i);//Here is the bug
    enemies[i].Move();
}

还有这里

代码语言:javascript
复制
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);
}

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

这应该是可行的:

代码语言:javascript
复制
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()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49351467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档