从数组中删除javascript

时间:2015-04-20 18:13:44

标签: javascript arrays object

你好,我的代码运行但是当我与星星碰撞时它会擦除我屏幕上的所有内容但是我需要它做的只是从屏幕上移除星星但保留其他所有内容因为我打算制作一个后来收集的每颗星的记分牌。

stars=[];
 stars.push({
   x: 420,
   y:  580,
width: 5,
height: 5

 });


function update() {

var score = 0; // score starts at 0

// check keys
if (keys[38] || keys[32]) {
    // up arrow or space
    if (!player.jumping && player.grounded) {
        player.jumping = true;
        player.grounded = false;
        player.velY = -player.speed * 2;
    }
}
if (keys[39]) {
    // right arrow
    if (player.velX < player.speed) {
        player.velX++;
    }
}
if (keys[37]) {
    // left arrow
    if (player.velX > -player.speed) {
        player.velX--;
    }
}

player.velX *= friction;
player.velY += gravity;

ctx.clearRect(0, 0, width, height);
ctx.fillStyle = "black";
ctx.beginPath();

player.grounded = false;
for (var i = 0; i < boxes.length; i++) {
    ctx.rect(boxes[i].x, boxes[i].y, boxes[i].width, boxes[i].height);

    var dir = colCheck(player, boxes[i]);



    if (dir === "left" || dir === "right") {
        player.velX = 0;
        player.jumping = false;
    } else if (dir === "bottom") {
        player.grounded = true;
        player.jumping = false;
    } else if (dir === "top") {
        player.velY *= -1;
    }

  }
for (var i = 0; i < stars.length; i++) {
    ctx.rect(stars[i].x, stars[i].y, stars[i].width, stars[i].height);

    var dir = colCheck(player, stars[i]);

    if(dir != null)
    {
delete stars[0];
//stars.splice(a);
//var resultObject = search.splice(0,1);
 }


     if (dir === "left" || dir === "right") {
        player.velX = 0;
        player.jumping = false;
    } else if (dir === "bottom") {
        player.grounded = true;
        player.jumping = false;
    } else if (dir === "top") {
        player.velY *= -1;
    }

}


  if(player.grounded){
     player.velY = 0;
}

player.x += player.velX;
player.y += player.velY;

ctx.fill();
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.width, player.height);

  requestAnimationFrame(update);
   }

2 个答案:

答案 0 :(得分:2)

替换

delete stars[0];

stars.splice(i,1);
i--;

我没有看到任何其他错误。

答案 1 :(得分:0)

您想要向后遍历数组。这是因为当你删除元素时,数组的长度会发生变化(最后元素的索引将减少一个),所以你当前的代码会跳过一些元素。另外,正如deme72所说,您将要使用.splice(index, count)从数组中删除项目。请参阅下面的更新代码:

for (var i = stars.length - 1; i >= 0; i--) {
    // Other code
    stars.splice(i, 1);
}