随机调用对象属性

时间:2015-11-11 03:21:47

标签: javascript jquery arrays

我有一个看起来像的对象:

var monsters = {
    zombies:  {
        name: "zombie",
        hitPoints: 10,
        loot: "magic knife"
    },
    skeleton: {
        name: "skeleton",
        hitPoints: 15,
        loot: "magic shield"
    },
    ghoul:  {
        name: "ghoul",
        hitPoints: 12,
        loot: "magic helm"
    }
};  

我试图设置一个随机选择变量中某个属性的函数。 (僵尸,骨架,食尸鬼)

以下是我所拥有的:

var travel = function(direction) {
        var newRoom = rooms[currentRoom.paths[direction]];
        if (!newRoom) {
            $("<p>You can't go that way.</p>").properDisplay();
        }
        else {
            currentRoom = newRoom;
            $("<p>You are now in the " + currentRoom.name + " Room.</p>").properDisplay();
                if (currentRoom.hasMonsters) {
                    function pickRand(monsters) {
                        var result;
                        var count = 0;
                        for (var prop in monsters)
                            if (Math.random() < 1/++count)
                                result = prop;
                            return $("<p>Holy Crap!  There's a" + result + "in here!</p>").properDisplay(); 

                    }
        }
        else {
            $("<p>Whew!  Nothing here.</p>").properDisplay();
        }
        }
    };

注意:hasMonsters位于单独的对象中。它确定特定房间是否有怪物。

如何随机选择其中一个怪物并插入输出?我猜测我错误地调用了这个对象,这就是为什么它不起作用的原因。

2 个答案:

答案 0 :(得分:4)

这样的事情会起作用吗?你可以将怪物作为一个对象,并使用Object.keys将你的键(在这种情况下是你的怪物)作为一个数组来获取。然后,这只是用Math.random挑选一个随机怪物的问题:

// so you have some object where the keys are your monsters
var monsters = { ghost: '..', skeleton: '..', donald_trump: '..'};

// grab your monsters above as an array
var monsterArray = Object.keys(monsters);

// pick your monster at random
var randomKey = Math.floor(Math.random() * monsterArray.length);

console.log('holy crap we found a ' + monsterArray[randomKey]);

答案 1 :(得分:1)

  

现在我明白了你在问什么。我想要名称属性调用。对   现在它会正确调用我猜的是整个对象。怎么样   我只叫这个名字吗?

尝试使用Object.keys()

var monsters = {
    zombies:  {
        name: "zombie",
        hitPoints: 10,
        loot: "magic knife"
    },
    skeleton: {
        name: "skeleton",
        hitPoints: 15,
        loot: "magic shield"
    },
    ghoul:  {
        name: "ghoul",
        hitPoints: 12,
        loot: "magic helm"
    }
};  

document.body.onclick = function() {
  
  var keys = Object.keys(monsters);
  var rand = Math.floor(Math.random() * keys.length)
  var res = monsters[keys[rand]];
  var key = Object.keys(res);
  var prop = res[key[Math.floor(Math.random() * key.length)]];
  console.log(res, prop);
  this.innerHTML += "<br>" + JSON.stringify(prop) + "<br>"
  
}
click