为什么我的MinArray实现不回收未使用的ID?

时间:2013-04-07 10:29:39

标签: javascript arrays

我正在构建一个基本的MinArray,即一个将已删除的ID推入队列的数组包装器, 并且在递增长度之前重新使用再循环的id;

然而,我的MinArray不回收id,它只是不断递增。

可以在此fiddle找到包含测试的完整代码。

此代码插入一个新值并返回指定的id:

MinArray.prototype.insert = function(val){
    var id;
    var recycledId = this._recycledIds.shift();
    if(recycledId){
        id = recycledId;
    }else{
        id = this._nextId++;
    }
    this._vals[id] = val;
    this._executeCallbacks(this.oninsert, this._vals[id]);
    this.length++;
    return id;
};

并且此代码从数组中删除了一个项目:

MinArray.prototype.remove = function(id){
    if(this._vals[id]){
        this._executeCallbacks(this.onremove, this._vals[id]);
        delete this._vals[id];
        this._recycledIds.push(id);
        this.length--;
        return true;
    }else{
        return false;
    }
};

或者,你知道我可以自由使用的任何好的现有实现吗?

2 个答案:

答案 0 :(得分:1)

解决方案非常简单:

MinArray.prototype.insert = function(val){
    var id;
    var recycledId = this._recycledIds.shift();
    if(typeof recycledId === 'number'){ // <<<<<
        id = recycledId;
    }else{
        id = this._nextId++;
    }
    this._vals[id] = val;
    this._executeCallbacks(this.oninsert, this._vals[id]);
    this.length++;
    return id;
};

答案 1 :(得分:1)

if(recycledId){更改为if(recycledId !== undefined){,因为您将其写为零的方式也是错误的 - 而它应该是正确的

编辑: 同样的错误也在remove函数中 - 如果_vals [id]包含零(或错误或空字符串),它将不会被删除。更好地将if(this._vals[id]){更改为if(this._vals[id] !== undefined){并向开发人员注意MinArray不能将'undefined'值包含为数据。