Javascript Array Splice Not working fine

Wasim A. picture Wasim A. · Jul 2, 2013 · Viewed 22.6k times · Source
var cache = [];
cache[0] = "0";
cache[1] = "1";
cache[2] = "2";
cache[3] = "3";
cache[4] = "4";
cache["r"] = "r";
console.log(cache.length);
for(key in cache){
    if(isNaN(key))continue;
    else cache.splice(key,1); // cache.splice(key) is working fine, ***
}
console.log(cache);

Question : in line *** Why splice(key) is working fine (Deleting All Elements with Numeric Index) and splice(key,1) not working fine (Not Deleting Elements with Numeric index). Even i have tried

splice(key,1) // Not working as splice(key)
splice(key--,1) // Even not working as splice(key)
splice(key,0) // not deleting any thing

You can copy and paste code in Firebug console for testing.

Answer

Guffa picture Guffa · Jul 2, 2013

It's not working because you are removing items from the array whil looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.

When I try it in Firefox, it only iterates over the keys 0, 1, 2 and r. Removing items while iterating makes it skip 3 and 4. The splice itself works fine, but it affects the loop so that some items are simply not in the iteration.

As you are actually looking for the indexes in the array by skipping non-numerical keys, you can just loop through the indexes instead. By looping through them backwards, you don't get the problem with the array changing while you loop through it:

var cache = ["0", "1", "2", "3", "4"];
cache.r = "r";
console.log(cache.length);
for (var i = cache.length - 1; i >= 0; i--) {
    cache.splice(i, 1);
}
console.log(cache);

Demo: http://jsfiddle.net/CguTp/1/