RomanK RomanK - 11 months ago 65
Javascript Question

Removing Last Item In Array, Deletes Whole Array

I have an if statement inside a for loop which loops through the whole array and displays the elements:

for (var i = 0; i < txtA.length; i++) {

if (txtA[i].y == height) {

The if statement checks the elements height compared to the canvas and removes the element. The problem is that all the elements in the array are removed when the if statement equals true. HELP!

Answer Source

Because you're doing a pop. Pop removes the last element of the array. If your first item hits the bottom then it's going to remove the last item in the array. It's going to loop over and keep removing the last item until it finally removes the first item that hit the bottom.

Use splice instead

txtA.splice(i, 1);