如何从游戏循环内的数组中删除对象(setInterval)

我有一个点击事件,它检查数组中的对象是否应该被删除(isSquashed),当它为真时,我们从数组列表中删除该对象,但是当出现这种情况时,我需要跳出循环或递减i值,基本上我想跳出for循环,在拼接数组对象后用newArray列表长度再次调用gameloop


我尝试了两种方式


向后迭代 for 循环

给出中断声明(获得非法中断声明)但它仍然没有发生在我身上所以有人可以帮我解决这个问题并让我知道我如何解决这个问题,


maingameloop = function(antsArray) {


  //inititialization


  // antsArray[i].draw();

  // antsArray[i].checkifSmashed();


  //gameloop

  if (this.isplaying) {

    console.log(this.score);

    for (let i = 0; i < antsArray.length; i++) {

      let gameloop = setInterval(() => {

          antsArray[i].move();

          antsArray[i].update(antsArray);


          if (antsArray[i].isSquashed) {

            this.score++;

            antsArray.splice(i, 1);

            // i--;

            clearInterval(gameloop);


            // this.isplaying = false ;

          }

        },

        this.FRAME_RATE,

      );

    }

  } else {

    //gameover

    // this.maingameloop(antsArray);

  }

}

从数组中删除对象时得到的 o/p 是:


Uncaught TypeError: Cannot read property 'move' of undefined


POPMUISE
浏览 166回答 3
3回答

德玛西亚99

循环间隔或超时绝不是一个好主意尝试这个var cnt = antsArray.lengthfunction ants() {&nbsp; if (cnt <= 0) {&nbsp; &nbsp; //gameover&nbsp; &nbsp; // this.maingameloop(antsArray);&nbsp; &nbsp; return;&nbsp; }&nbsp; if (this.isplaying) {&nbsp; &nbsp; console.log(this.score);&nbsp; &nbsp; antsArray[cnt].move();&nbsp; &nbsp; antsArray[cnt].update(antsArray); // ???&nbsp; &nbsp; if (antsArray[cnt].isSquashed) {&nbsp; &nbsp; &nbsp; this.score++;&nbsp; &nbsp; &nbsp; cnt--;&nbsp; &nbsp; }&nbsp; &nbsp; setTimeout(play, this.FRAME_RATE);&nbsp; }}

撒科打诨

我清除了 setInterval 然后我检查了条件并添加了一个休息时间,这不会是非法的,因为我超出了时间间隔,所以它对我有用,谢谢大家的建议maingameloop = 函数(antsArray){&nbsp; &nbsp; //inititialization&nbsp; &nbsp; // antsArray[i].draw();&nbsp; &nbsp; // antsArray[i].checkifSmashed();&nbsp; &nbsp; //gameloop&nbsp; &nbsp; if (this.isplaying) {&nbsp; &nbsp; &nbsp; for (let i = 0; i< antsArray.length;&nbsp; i++) {&nbsp; &nbsp; &nbsp; let gameloop = setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; antsArray[i].move();&nbsp; &nbsp; &nbsp; &nbsp; antsArray[i].update(antsArray);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (antsArray[i].isSquashed) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.score++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(gameloop);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; , this.FRAME_RATE);&nbsp; &nbsp; if(antsArray[i].isSquashed ){&nbsp; &nbsp; &nbsp; antsArray.splice(i, 1);&nbsp; &nbsp; &nbsp;break;&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; }else {&nbsp; &nbsp; &nbsp; //gameover&nbsp; &nbsp; &nbsp; // this.maingameloop(antsArray);&nbsp; &nbsp; }&nbsp; }

四季花海

避免在循环内使用 setInterval ,因为它需要异步回调才能在同步循环内运行,而同步循环将始终显示这些类型的错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript