4
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.

Wasim A.
  • 9,660
  • 22
  • 90
  • 120
  • 3
    Can you clarify "not working"? What happens when you try the code, and how does it differ from what you expect? Do you get any error message? – Guffa Jul 02 '13 at 15:40
  • splice function delete element from array. Its should delete all element with numeric index but its removing few one – Wasim A. Jul 02 '13 at 17:33
  • so splice expects me to provide a numeric index, so (n,x) mean start from numeric index n and remove x values after index n. if n is not numeric but a key then no need of x. So it work fine x is removed. – Wasim A. Jul 21 '13 at 06:49
  • No, it doesn't work without an index. If you only specify one parameter, that is used as the index, and it will remove all items to the end of the array. If you use the method with a key instead of an index and it seems to work, that is just a coincidence because the specific values that you used happened to give the same result. – Guffa Jul 21 '13 at 12:55

3 Answers3

15

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/

vsync
  • 118,978
  • 58
  • 307
  • 400
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • removing in reverse is a good idea but i am using associative array. you deserve – Wasim A. Jul 02 '13 at 18:23
  • my question is why splice(key,1) is not working on same place where splice(key) is working very fine. – Wasim A. Jul 02 '13 at 18:24
  • @Wasim: Using `splice(key)` doesn't work, it only gives the same result in this case, as the code is attempting to removing all the items. It will remove all items from the array in the first iteration, it will not remove one item at a time. – Guffa Jul 02 '13 at 21:37
3

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--;
            }
        }
Eric Beaulieu
  • 1,054
  • 7
  • 11
  • key or index is same in my case. i am handling associative array of javascript, not numeric array. Please search google for associative array and JSON to learn more :) – Wasim A. Jul 02 '13 at 17:31
  • According to the answer to this question http://stackoverflow.com/questions/948894/splicing-a-string-indexed-array-in-javascript then you can use delete instead of splice, that doesn't answe why splice(key,1) doesn't work, but apparently its the proper way to delete from a string indexed array – Eric Beaulieu Jul 02 '13 at 17:56
  • After researching associative arrays, I stand by my answer. Since `cache` is not an array, you cannot expect splice to behave like it is. – Eric Beaulieu Jul 02 '13 at 18:13
  • delete is for JSON object not for JS array actually – Wasim A. Jul 02 '13 at 18:17
  • exactly, delete is for a JSON object, your `cache` object is a JSON object, not an array – Eric Beaulieu Jul 02 '13 at 20:01
2

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.

Wasim A.
  • 9,660
  • 22
  • 90
  • 120
  • I'm looking for a good way to remove elements from an associative array as well. According to this answer, [this](http://jsfiddle.net/AL5LG/) should work, however, as seen in the console, it does nothing to the associative array. Using `delete` will work, as in [this example](http://jsfiddle.net/AL5LG/2/) (although the `.length` property seems to function abnormally). – JVE999 Jun 26 '14 at 18:07
  • splice(key) should work and splice(key,x) will not work. Just remove second parameter from splice function. – Wasim A. Jun 26 '14 at 18:40
  • what answer you found correct, let me check if that is better answer then i will select that one. – Wasim A. Jun 26 '14 at 18:41