JavaScript -- trying to use a loop to delete certain items in an array, but it deletes all items -


i first tried foreach loop delete items array, later learned shouldn't this. tried make 1 normal loop. cycle through array containing bullets, , delete them when go outside game area.

for (i = 0; < playerbullets.length; i++) { console.log(playerbullets[i].x); console.log(playerbullets[i]); if (playerbullets[i].x > 800 || playerbullets[i].x < 0 || playerbullets[i].y > 600 || playerbullets[i].y < 0 ) { playerbullets.splice(i); } }      

the console correctly shows [i] in full, , brings list of contents of array. however, [i].x console log displays 1 value, rather "x" value of each object in array.

then first bullet goes out of bounds, bullets disappear. frustrating, , highly ineffective killing zombies.

i have tried looping backwards through loop, seems recommended way tells me undefined.

any ideas? feel i'm making simple error, because i'm using same structure code on tutorial sites, "should work".

thank you!

you should passing 2 parameters .splice() method, start index (which you're doing) , number of elements delete (which you're not doing):

playerbullets.splice(i, 1); 

the reason looping backwards idea if remove item middle of array while looping through array index i out of sync - index of each item after removed 1 decreases 1 on next loop iteration i++ skip on element after removed one. if looping forwards you'd need decrease i 1 after deleting item. if looping backwards isn't problem.

i'm guessing got undefined when trying loop backwards because started playerbullets.length, 1 more index of last item. need start playerbullets.length - 1 , go down 0:

for (i = playerbullets.length - 1; >= 0; i--) {   if (playerbullets[i].x > 800 || playerbullets[i].x < 0 || playerbullets[i].y > 600 || playerbullets[i].y < 0 ) {     playerbullets.splice(i, 1);   } }   

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -