从对象获取索引

时间:2015-11-23 11:33:36

标签: javascript object indexing

所以我创建了一个基于文本的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
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你需要这个:

var keys = Object.keys(abilitiesObject);

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

您可能还需要Object.keys polyfill与旧版浏览器兼容: 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]();
}