为什么 splice 从数组中删除所有元素?

问题描述

所以我正在尝试制作这个游戏(我在视频中看到过),但我想以不同的方式制作它,但我被卡住了。我有这个带有射弹的阵列。基本上,每次弹丸移出屏幕时,我都想从阵列中删除该弹丸。问题是当射弹击中屏幕时,所有射弹都会被删除

代码

function animate(){

    requestAnimationFrame(animate);
    c.clearRect(0,width,height);
    player.draw();
    
    //shoot on click
    addEventListener('click',function(event){
        mousex = event.clientX;
        mousey = event.clientY;
        let angle = Math.atan2(mousey - player.y,mousex - player.x);
        projectiledx = Math.cos(angle) * 8;
        projectiledy = Math.sin(angle) * 8; 
        projectileArray.push(new Projectile(width/2,height/2,10,projectiledx,projectiledy,black));

    })
    for(let i = 0; i < projectileArray.length; i++){
        projectileArray[i].update();
        if(projectileArray[i].x + projectileArray[i].radius < 0 || projectileArray[i].x - projectileArray[i].radius >= width){
            projectileArray[i].splice(i,1);
         }
         if(projectileArray[i].y + projectileArray[i].radius < 0 || projectileArray[i].y - projectileArray[i].radius >= height){
            projectileArray[i].splice(i,1);
         }
    }
}
animate();

解决方法

我可以在这里看到至少两个问题:

  1. [i]之前不应该有.splice

  2. 您正在使用 for 循环迭代数组,并且您想在该循环中修改该数组的长度 - 对我来说这看起来是个坏主意.. 最好将要删除的项目列表和在该循环之后......在另一个循环中删除它们(从最后一个开始),如下所示:

     var removalList = [];
     for(let i = 0; i < projectileArray.length; i++){
         projectileArray[i].update();
         if(
             projectileArray[i].x + projectileArray[i].radius < 0 ||
             projectileArray[i].x - projectileArray[i].radius >= width ||
             projectileArray[i].y + projectileArray[i].radius < 0 ||
             projectileArray[i].y - projectileArray[i].radius >= height
         ){
             removalList.push(i);
          }
     }
    
     for(let i=removalList.length; i>0; i--){
         projectileArray.splice( removalList[i-1],1 );
     }