2017-03-02 27 views
-2

我想引用一個數組中的索引,但gameObjects [1]返回爲undefined。 gameObjects是一組對象。你不能連接一個字符串與一個JavaScript對象中的函數調用?

var gameObjects = [enemy,treasure]; 


var mysteryBlock = { 
name: "Mystery Block", 
output:"produces " + gameObjects[1] 

} 

var enemy = { 
output: "an enemy" 
} 

var treasure = { 

    output: "a treasure" 

} 

console.log("your mystery cube " + mysteryBlock.output) 

回到未定義狀態。

+0

也許你的意思'輸出: 「生產」 + gameObjects [1] .output' – bejado

+0

在哪裏,函數調用你的稱號指什麼? – Lucero

回答

1

在使用它們之前,您應該定義enemytreasure。它不工作,因爲你需要引用對象的output屬性:

var enemy = { 
    output: "an enemy" 
} 

var treasure = { 
    output: "a treasure" 
} 

var gameObjects = [enemy,treasure]; 


var mysteryBlock = { 
    name: "Mystery Block", 
    output:"produces " + gameObjects[1].output 
} 


console.log("your mystery cube " + mysteryBlock.output); 

Here it is working

+1

變量提升。我們甚至可以在定義它們之前使用它們 –

+0

我改變了我的措辭,說他應該先定義它們。我意識到它的工作原理,我只是建議沒有理由不按順序做 – Pabs123

+1

對不起,我意識到變量提升在這種情況下不起作用。該命令是必要的。 JavaScript只會提升聲明,而不是初始化。 –

1

gameObjects變量是對象的數組,看起來像:

[{ 
    "output": "an enemy" 
}, 
{ 
    "output": "a treasure" 
}] 

通過調用它gameObjects[1],您將收到一個對象。爲了得到結果,你必須指定key,在你的情況下將是output

var enemy = { 
 
    output: "an enemy" 
 
} 
 

 
var treasure = { 
 
    output: "a treasure" 
 
} 
 

 
var gameObjects = [enemy, treasure]; 
 

 
var mysteryBlock = { 
 
    name: "Mystery Block", 
 
    output: "produces " + gameObjects[1].output //mentioned line of code 
 
} 
 

 
console.log("your mystery cube " + mysteryBlock.output)

相關問題