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?
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?
Share Improve this question edited Jun 13, 2013 at 18:24 Thomas Andreè Wang asked Jun 13, 2013 at 18:11 Thomas Andreè WangThomas Andreè Wang 3,4416 gold badges39 silver badges55 bronze badges 2- see stackoverflow./q/281264/1066234 – Avatar Commented May 4, 2015 at 11:04
- late and its solved :) – Thomas Andreè Wang Commented May 4, 2015 at 11:06
1 Answer
Reset to default 8Don'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);