2015-06-16 105 views
0

而且我有一個讀取關卡數據的函數。這是有問題的片段;演員是一個數組,我正在循環播放,直到找到類型播放器的演員。Javascript,console.log打印打印對象,但屬性未定義

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或任何東西。認爲這可能是執行順序,有人可以向我解釋這個和解決方案嗎?如果它是執行命令待辦事項,將不勝感激。

非常感謝你, 陰雨

回答

2

你得到undefined,因爲當您過濾actor數組,你會得到一個新的數組作爲結果。因此console.log(this.player)輸出數組,而不是單個對象。

您需要獲取數組this.player的第一個元素才能輸出其pos屬性。

事情是這樣的:

if(this.player.length > 0) 
    console.log(this.player[0].pos); 
0

使用reduce,而不是filter單個球員。

this.player = this.actors.reduce(function(current, actor) { 
     return actor.type === 'player' ? actor : current; 
    });