Search code examples
javascriptjqueryarrayssplicefor-in-loop

Javascript Array Splice Not working fine


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.


Solution

  • Splice expects first index as numeric,

    splice(n,x); //n and x are numeric here  
    

    It will start removing values from array starting at index n and remove x values after index n.

    Now if n is not numeric but a key then no need of x because x can move pointer forward in a numeric-indexed array only not associative array. So removing x from splice(n,x) will make function similar to splice(key) etc and so it will work fine.