有没有办法使用函数参数的值声明变量
is there a way to declare a variable using the value of a functions parameter
我需要使用通过函数发送的名称来声明变量
作为 parameter/argument
function CreateDroptable(npcName) {
Droptable.npcName = new Droptable();
}
如果输入 "CreateDroptable(goblin)",我想要它做的是
它将创建变量 "Droptable.goblin"
但它声明为 "Droptable.npcName"
有办法解决吗?
function CreateDroptable(npcName) {
Droptable[npcName] = new Droptable();
}
应该可以解决问题。 String/array/bracket 符号就是出于这个原因。 :)
编辑:
我注意到您提到相应地使用它:CreateDroptable(goblin)
这将无法正常工作。它应该像这样使用:
CreateDroptable("goblin");
其中 goblin 是字符串,而不是变量。
尝试...
function CreateDroptable(npcName) {
Dreoptable[npcName] = new Droptable();
}
然后,当声明...
CreateDroptable("goblin");
通话变成...
Droptable["goblin"](1,2,3);
如果你想使用直线物体而不是variables/arrays。然后你必须走面向对象的路线 - 这与你所做的有点不同。
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);
整体看起来干净多了,是传统的做事方式。但它可能不完全是你要找的。
但愿对您有所帮助。
编码愉快!
我需要使用通过函数发送的名称来声明变量 作为 parameter/argument
function CreateDroptable(npcName) {
Droptable.npcName = new Droptable();
}
如果输入 "CreateDroptable(goblin)",我想要它做的是 它将创建变量 "Droptable.goblin" 但它声明为 "Droptable.npcName"
有办法解决吗?
function CreateDroptable(npcName) {
Droptable[npcName] = new Droptable();
}
应该可以解决问题。 String/array/bracket 符号就是出于这个原因。 :)
编辑:
我注意到您提到相应地使用它:CreateDroptable(goblin)
这将无法正常工作。它应该像这样使用:
CreateDroptable("goblin");
其中 goblin 是字符串,而不是变量。
尝试...
function CreateDroptable(npcName) {
Dreoptable[npcName] = new Droptable();
}
然后,当声明...
CreateDroptable("goblin");
通话变成...
Droptable["goblin"](1,2,3);
如果你想使用直线物体而不是variables/arrays。然后你必须走面向对象的路线 - 这与你所做的有点不同。
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);
整体看起来干净多了,是传统的做事方式。但它可能不完全是你要找的。
但愿对您有所帮助。
编码愉快!