簡體   English   中英

javascript從數組中刪除

[英]javascript removing from array

你好,我的代碼運行了,但是當我與星星碰撞時,它會擦除​​屏幕上的所有內容,但是我需要做的就是從屏幕上移除星星,但將其他所有內容都保留在原處,因為我計划為每個記分板做一個記分板后來收集的星星。

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);
   }

更換

delete stars[0];

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

我沒有發現其他任何錯誤。

您需要向后遍歷數組。 這是因為刪除元素時數組的長度將更改(並且元素的索引將減少一),因此您當前的代碼將跳過某些元素。 另外,正如deme72所說,您將要使用.splice(index, count)從數組中刪除項目。 請參閱下面的更新代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM