سؤال

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.

هل كانت مفيدة؟

المحلول 3

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.

نصائح أخرى

It's not working because you are removing items from the array while 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/

1) cache["r"] = "r"; does not add an element to your array, it adds a property to the cache object

To initialize an array you can use some thing like

var cache = ["0", "1", "2", "3", "4", "r"];

or

var cache = new Array();
cache.push("0");
cache.push("1");
cache.push("2");
cache.push("3");
cache.push("4");
cache.push("r");

Since your cache object is not an array, you cannot expect splice to behave as it would for an array.

2) splice expects an index as the first argument, not a key

see http://www.w3schools.com/jsref/jsref_splice.asp

So you could use this to remove all numeric values:

for (var i = 0; i < cache.length; i++) {
        if (!isNaN(cache[i])) {
            cache.splice(i, 1); // cache.splice(key) is working fine, ***
                i--;
            }
        }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top