RomanK RomanK - 2 months ago 17
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++) {
txtA[i].update();
txtA[i].show();

if (txtA[i].y == height) {
txtA.pop();
console.log(txtA.length);
}
}


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

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);