编辑:我也为您对该脚本进行了一些改进 - 只是为了强调可以做什么:
var Monster = {
monsters: {
rat: {
attack: [5, 9],
defense: [3, 5],
health: [5, 10],
title: "Rat"
},
spider: {
attack: [6, 11],
defense: [4, 5],
health: [4, 6],
title: "Spider"
}
},
create: function(type) {
// choose type at random if not specified
if(typeof type !== "string") {
var keys = [ ];
for(var key in this.monsters) {
if(this.monsters.hasOwnProperty(key)) {
keys.push(key);
}
}
type = keys[Math.floor(Math.random() * keys.length)];
}
// check if given monster type exists
if(typeof this.monsters[type] === "undefined") {
throw new TypeError('invalid monster type "' + type + '"');
}
var monster = { };
/*
* This allows you to add new attributes and not have to change any
* of this code, except the attributes object for each monster.
*/
for(var attribute in this.monsters[type]) {
if(this.monsters[type].hasOwnProperty(attribute)) {
var a = this.monsters[type][attribute];
if(typeof a == "object") {
a = Math.floor(Math.random() * (a[1] - a[0] + 1) + a[0]);
}
monster[attribute] = a;
}
}
return monster;
}
};
console.log(Monster.create('rat'));
console.log(Monster.create('spider'));
console.log(Monster.create());
这就是我要做的,这很好,很简单,并且可以在将来轻松添加怪物和属性:
var Monster = {
monsters: {
rat: {
attack: [5, 9],
defense: [3, 5],
},
spider: {
attack: [6, 11],
defense: [4, 5]
}
},
create: function(type) {
// check if given monster type exists
if(typeof this.monsters[type] === "undefined") {
throw new TypeError('invalid monster type "' + type + '"');
}
var monster = { };
/*
* This allows you to add new attributes and not have to change any
* of this code, except the attributes object for each monster.
*/
for(var attribute in this.monsters[type]) {
if(this.monsters[type].hasOwnProperty(attribute)) {
var a = this.monsters[type][attribute];
monster[attribute] = Math.floor(Math.random() * (a[1] - a[0] + 1) + a[0]);
}
}
return monster;
}
};
console.log(Monster.create('rat'));
console.log(Monster.create('spider'));