自定义数组函数不接受参数

时间:2013-10-16 22:44:35

标签: javascript arrays prototype

我正在调试代码并看到在调用erase()时正确填充了entites和_deferredKill数组。问题是参数'item'没有被定义,即使我看到参数'gGameEngine._deferredKill [i]'被传入。为什么它不接受我传递的被杀死的实体?我正在使用John Resig的simple javascript inheritance

//In GameEngine.js
GameEngineClass = Class.extend({

    entities: [],
    _deferredKill: [],

    .........

    for (var k = 0; k < gGameEngine._deferredKill.length; k++){
        gGameEngine.entities.erase(gGameEngine._deferredKill[i]);
    }
}
gGameEngine = new GameEngineClass();

//in core.js, GameEngineClass is extended from this.  
Array.prototype.erase = function(item) {
for (var i = this.length; i--; i) {
    if (this[i] === item) this.splice(i, 1);
}
    return this;
};

1 个答案:

答案 0 :(得分:1)

访问数组索引时,您正在使用变量i。此变量不存在,因此作为参数传递的item的值也是undefined

您应该将gGameEngine._deferredKill[i]替换为gGameEngine._deferredKill[k]以匹配您的循环。