Bug in JS for loops?

Bug in JS for loops?
0.0 0


When I predefine arr.length (like I did below) the function works, but when I don’t (i.e. when I replace times with arr.length) the function equals [5,6,7]. Does anyone know if this is a bug? function dropElements(arr, func) {
var times=arr.length;
for(var i=0; i < times; i++){
return arr;
dropElements([1, 2, 3, 4,5,6,7], function(n) {return n > 5;}); //equals [6,7] w/ times predefined


edit: strange I see the problem. I wonder why you are using an index at all since the array will either end up empty or you will break. while(arr.length > 0) works for me. Have you tried logging i and arr.length or really everything at each step of the loop to see whats going on?

Figured it out: your array is getting smaller than the number of items you have iterated over. Say you have 10 items in the array and 8 of them need to be deleted. once you get half way through your array the length of the array will be 5 and i will be 5. on the next step the length will be 4 and i will be 6 and you will break out without testing all the items even though you need to keep going. Storing the number of times you need to loop at most seems fine.


I totally forgot that shift removes the first value from the array. Thanks a lot