Phaser - 用于循环抛出“TypeError:无法读取未定义的属性'长度'

时间:2015-12-28 00:52:29

标签: javascript arrays phaser-framework

我正在尝试使用Phaser.js构建一个简单的游戏,我在遍历数组时遇到了一个问题。

var EnemyGroup = function(enemies) {
    game.add.group();
    this.enemies = enemies;
    this.addEnemies(this.enemies);
    //return this;
};

EnemyGroup.prototype = Object.create(Phaser.Group.prototype);
EnemyGroup.prototype.constructor = EnemyGroup;

EnemyGroup.prototype.addEnemies = function(enemies) {
    console.log(enemies.length);
    for (var i=0;i<enemies.length;i++) {
        console.log(i);
        this.add(enemies[i]);
    }
    console.log('done');
};

上面,当我创建EnemyGroup的实例时,我调用函数this.addEnemies。在循环遍历数组之后,抛出错误: TypeError: Cannot read property 'length' of undefined

为了理解原因,我让控制台记录了数组的计数,并在循环时记录它当前所在的索引。数组中只有一个对象。

输出结果为:

1&lt; -the array count(correct)

0&lt; - 它所在的索引(也正确,因为数组中只有一个对象)

TypeError: Cannot read property 'length' of undefined&lt; -the error

我通过让控制台记录Done来检查是否在for循环之外引起了错误...但是它没有记录这个,所以我知道它在{{1 }}

2 个答案:

答案 0 :(得分:1)

简单:您在this

上引用enemies时忘记添加addEnemies()
var EnemyGroup = function(enemies) {
    game.add.group();
    this.enemies = enemies;
    this.addEnemies(this.enemies);
    //return this;
};

EnemyGroup.prototype = Object.create(Phaser.Group.prototype);
EnemyGroup.prototype.constructor = EnemyGroup;

EnemyGroup.prototype.addEnemies = function(enemies) {
    console.log(this.enemies.length);
    for (var i=0;i<this.enemies.length;i++) {
        console.log(i);
        this.add(this.enemies[i]);
    }
    console.log('done');
};

相关问题:Why is there no implicit this in JavaScript

答案 1 :(得分:0)

var EnemyGroup = function(game) {
    Phaser.Group.call(this, game);
};

EnemyGroup.prototype = Object.create(Phaser.Group.prototype);
EnemyGroup.prototype.constructor = EnemyGroup;

EnemyGroup.prototype.addEnemies = function(enemies) {
    for (var i=0;i<enemies.length;i++) {
        if (enemies[i]) {
            this.add(enemies[i]);
        }
    }
};

然后在main.js:

enemyGroup = new EnemyGroup(game);
enemyGroup.addEnemies(pikas);