数组中的对象随机提醒

时间:2013-12-31 05:22:19

标签: javascript

我已经使用javascript构建了这个代码,这些代码会生成一些名为monster的对象。然后我把这些怪物放在一个数组中,最后我试图随机地将一个怪物叫到控制台。不幸的是,它在我的控制台日志中显示为undefined。关于如何在每次刷新页面时在控制台日志中获取随机怪物的任何建议?

function Monster(type, level, mAttack, mAgility, mHP) {
    this.type = type;
    this.level = level; 
    this.mAttack = mAttack;
    this.mAgility = mAgility;
    this.mHP = mHP; 
}
Monster.prototype.logInfo = function() {
    console.log("I am a : ", this.type);
    console.log("I am level : ", this.level);
    console.log("I have the attack of : ", this.mAttack);
    console.log("I have the agility : ", this.mAgility);
    console.log("I have the health : ", this.mHP); 
}

var troll = new Monster("troll", 1, 10, 10, 10);
var skeleton = new Monster("skeleton", 1, 10, 10, 10);
var slime = new Monster("slime", 1, 10, 10);
var boar = new Monster("boat", 1, 10, 10);


var monsterList = new Array();
monsterList[0] = troll;
monsterList[1] = skeleton;
monsterList[3] = slime;
monsterList[4] = boar;


var summonRandomMonster = function (){
     monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}
console.log(monsterSummoner);

3 个答案:

答案 0 :(得分:3)

您创建了一个函数但从不调用它。因此,从未设置过monsterSummoner。

// THIS IS NEVER CALLED
var summonRandomMonster = function (){
     monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}

console.log(monsterSummoner);

试试这个。请注意,现在函数被调用,值已设置。

var monsterSummoner;
var summonRandomMonster = function (){
     monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
}

summonRandomMonster();
console.log(monsterSummoner);

答案 1 :(得分:0)

你很接近......改变你的最后四行 -

var monsterList = [troll,skeleton,slime,boar];

var summonRandomMonster = function (){
   monsterSummoner = monsterList[Math.floor(Math.random() * monsterList.length)];
   console.log(monsterSummoner);
}
for (var i = 0; i < 100; i++) {
  summonRandomMonster();
}

答案 2 :(得分:0)

此代码中至少存在两个问题。未定义变量“monsterSummoner”,并且不调用函数“summonRandomMonster”。