Skip to content Skip to sidebar Skip to footer

Javascript Splice Changing Earlier Values In An Array

I am creating a game that randomly displays circles onto a canvas. The circles objects are added to an array and whenever the player collides with one of them I want to remove that

Solution 1:

It is quite common to run into trouble when modifying an array which you are looping.

For example, if you remove the item at position i, then the later items will shift left, so the next item will now sit in position i, but because the next iteration of your loop inspects i+1, that item will be skipped!

Now you could do i--; after the splice, to ensure you inspect the new item in position i on the next iteration, but a simpler solution is simply to loop backwards. Then operations which affect the rest of the list will not be an issue.

for(var i = currentGame.items.length; i--; )

Anyway, I am concerned by something else in your code:

position = currentGame.items.indexOf(i);

Don't we already know that the position of the current item is i? This indexOf searches the list for an item with the valuei. I imagine position will get the value -1 when the indexOf search fails. I think what you really mean here is:

var position = i;

Finally, if you don't enjoy console.log you can try putting this inside your if block:

debugger;

That manually sets a breakpoint in your code, so you can inspect the values of the variables to see what is going wrong. You will need to have your browser's debugger or "dev tools" panel open. Don't forget to remove the statement when you are finished!

Post a Comment for "Javascript Splice Changing Earlier Values In An Array"