Javascript,console.log打印对象,但属性未定义
我有一个函数,可以读取级别数据。这是有问题的片段;actors是一个数组,我在上面循环,直到找到一个类型为player的actorJavascript,console.log打印对象,但属性未定义,javascript,console,undefined,execution,Javascript,Console,Undefined,Execution,我有一个函数,可以读取级别数据。这是有问题的片段;actors是一个数组,我在上面循环,直到找到一个类型为player的actor function Level(plan) { //Cut snippet.......... this.player = this.actors.filter(function(actor) { return actor.type == "player"; }); console.log(this.player); /
function Level(plan) {
//Cut snippet..........
this.player = this.actors.filter(function(actor) {
return actor.type == "player";
});
console.log(this.player);
//................
}
玩家对象
function Player(pos) {
this.pos = pos
this.size = new Vector(0.8, 1.5);
this.speed = new Vector(0, 0);
}
Player.prototype = new Actor();
Player.prototype.type = "player"
问题在于,在控制台中
console.log(this.player)
将显示所有正确的详细信息,但当我尝试记录位置时,例如
console.log(this.player.pos)
我没有定义。这是一个简单的程序,我没有使用ajax或任何东西。虽然这可能与执行顺序有关,但有人能向我解释一下这一点并提出解决方案吗?如果是执行命令,请解释
多谢各位,
雨您会得到
未定义的
,因为当您过滤参与者
数组时,您会得到一个新数组。所以console.log(this.player)
输出一个数组,而不是一个对象
您需要获取数组的第一个元素this.player
,以输出其pos
属性
大概是这样的:
if(this.player.length > 0)
console.log(this.player[0].pos);
对单个播放器使用
reduce
而不是filter
this.player = this.actors.reduce(function(current, actor) {
return actor.type === 'player' ? actor : current;
});