2015-11-23 132 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