Why Is Splice Removing All The Elements From An Array?
So I am trying to make this game(which I've seen in a video), but I'd like to make it differently, and I am stuck. I have this array with projectiles. Basically, every time a proje
Solution 1:
I can see at least two problems here:
there should not be
[i]
before.splice
You are iterating the array with for loop and whithin that loop you want to modify the length of that array - it looks like a bad idea to me.. Better take a list of items to remove and after that loop ...remove them (begining from the last) in another loop like this:
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 ); }
Post a Comment for "Why Is Splice Removing All The Elements From An Array?"