最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Array of functions cleanup of empty slots - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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);

发布评论

评论列表(0)

  1. 暂无评论