2015-11-23 184 views
0

所以我創建了一個基於文本的RPG並且有一個包含玩家攻擊函數的對象。我想讓玩家輸入函數的索引來調用它。我試圖爲此使用for循環,但據我所知,您不能使用變量調用函數。有任何想法嗎? 這裏是我卡上的代碼 - 我會後下面的全碼:從對象獲取索引

function playHit(skill) 
{ 
    moveIndex = prompt("Your turn! Enter the number of the move you want to use.") 
    moveChosen = abilitiesObject[moveIndex] 
    for (move in moveList) 
    { 
     if (move === moveChosen) 
     { 
      moveList.move 
     } 
    } 
} 

全碼:

abilities = ["0. Slash", " 1. Push"] 
abilitiesObject = ["Slash", "Push"] 
function getMoves() 
{ 
    document.getElementById("moves").innerHTML = abilities 
} 
var moveList = new Object() 
moveList.Slash = function(damage) 
{ 
    if (damage < 5) 
    { 
     Poutcome = 0 
    } 
    else if (damage >= 5) 
    { 
     Poutcome = 1 
    } 
    Psmackdown = (Poutcome + att) - eDef 
    alert("You swing wildly! The monster takes " + Psmackdown + " points of damage.") 
    eHp = eHp - Psmackdown 
} 

moveList.Push = function(damage) 
{ 
    if (damage < 5) 
    { 
     Poutcome = -1 
    } 
    else if (damage > 9) 
    { 
     Poutcome = 2 
     alert("You shove the monster into a spike pit!") 
    } 
    else 
    { 
     Poutcome = 0 
    } 
    Psmackdown = (Poutcome + att) - eDef 
    alert("You shove the monster with all your might! The monster takes " + Psmackdown + " points of damage") 
} 


function playHit(skill) 
{ 
    moveIndex = prompt("Your turn! Enter the number of the move you want to use.") 
    moveChosen = abilitiesObject[moveIndex] 
    for (move in moveList) 
    { 
     if (move === moveChosen) 
     { 
      moveList.move 
     } 
    } 
} 
+0

你解決問題了嗎?我的解決方案幫助你? –

回答

2

你需要這樣的:

var keys = Object.keys(abilitiesObject); 

參考: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/keys

您可能還需要Object.keys填充以與舊版瀏覽器兼容: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/keys#Polyfill

看看這個:

var player = { 
 
    
 
    moves: { 
 
    push: function() { 
 
     document.write('Push!!'); 
 
    }, 
 
    
 
    smash: function() { 
 
     document.write('Smash!!'); 
 
    } 
 
    } 
 
}; 
 

 
var abilities = Object.keys(player.moves); 
 

 

 
var move = prompt("Your turn! Enter the number of the move you want to use.\r\n Options: " + abilities); 
 

 
// Execute 
 
if (player.moves[move]) { 
 
    player.moves[move](); 
 
}

+0

'Object.keys()'不保證順序 – Ramanlfc