我正在尝试使用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 }}
答案 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');
};
答案 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);