有没有办法使用函数参数的值声明变量

时间:2015-02-17 22:19:26

标签: javascript function variables

我需要使用通过函数发送的名称声明变量 作为参数/参数

function CreateDroptable(npcName) {
    Droptable.npcName = new Droptable();
}

我想要做的就是输入" CreateDroptable(goblin)" 它会创建变量" Droptable.goblin" 但相反,它声明它像" Droptable.npcName"

无论如何要解决它?

3 个答案:

答案 0 :(得分:1)

function CreateDroptable(npcName) {
    Droptable[npcName] = new Droptable();
}

应该做的伎俩。字符串/数组/括号表示法就是出于这个原因。 :)

编辑:

我注意到你提到了相应地使用它:CreateDroptable(goblin)这不会按原样运作。它应该像这样使用:

CreateDroptable("goblin");

其中精灵是一个字符串,而不是一个变量。

答案 1 :(得分:0)

尝试......

function CreateDroptable(npcName) {
  Dreoptable[npcName] = new Droptable();
}

然后,宣布......

CreateDroptable("goblin");

呼叫变为......

Droptable["goblin"](1,2,3);

答案 2 :(得分:0)

如果要使用直接对象而不是变量/数组。然后你必须走向面向对象的路线 - 这与你所做的有点不同。

function npc(type, health, strength) {
    this.type= type;
    this.health= health;
    this.strength= strength;
}

var goblin= new npc("Goblin", 100, 50);
var bat = new npc("Bat", 65, 1);

这整体看起来更清洁,是传统的做事方式。但它可能并不完全是你想要的。

希望它有所帮助。

快乐的编码!

相关问题