2

im having a problem, i have a array of functions which is frequently added to and removed from.

But when i do a foreach on the array it says that the index don't exist.

Input: arr[arr.length] = function () { Func() };

Remove: delete arr[indexToRemove];

for don't work now so i use a foreach for (key in arr)

I'm getting a feeling that it is possible to overflow on the index so to prevent this i would like to find empty array positions and reposition the items in it. This is what I'm thinking for cleanup atm.

    var temp = new Array();
    var count = 0;
    for (key in arr) {
        if (arr[key] != null) {
            temp[count] = arr[key];
            count++;
        }
    }
    arr = temp;

Is there a better solution and does a empty array of functions slot look like null?

Thomas Andreè Wang
  • 3,379
  • 6
  • 37
  • 53

1 Answers1

8

Don't use a for...in loop to iterate over an array; use a standard counting for loop. Do use Array.push() instead of arr[arr.length] = cont to add new values. Also don't use delete to remove an element from an array; use Array.splice().


Input: arr.push(cont);
Remove: arr.splice(indexToRemove, 1);

Matt Ball
  • 354,903
  • 100
  • 647
  • 710