0

I need to declare a variable using a name that is sent through a function as a parameter/argument

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

what I want this to do is if typed "CreateDroptable(goblin)" it would create the variable "Droptable.goblin" but instead it declares it like "Droptable.npcName"

Is there anyway to fix it?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199

3 Answers3

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

should do the trick. String/array/bracket notation is there for this very reason. :)

Edit:

I noticed that you mentioned using it accordingly: CreateDroptable(goblin) which will not work as is. it should be utilized like so:

CreateDroptable("goblin");

where goblin is a string, rather than a variable.

Jesse Kernaghan
  • 4,544
  • 2
  • 18
  • 25
0

Try ...

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

Then, when declaring ...

CreateDroptable("goblin");

Calling becomes ...

Droptable["goblin"](1,2,3);
rfornal
  • 5,072
  • 5
  • 30
  • 42
0

If you want to use straight objects instead of variables/arrays. Then you have to go object-orientated route - which is a bit different to what you have done.

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);

This overall looks a lot cleaner, and is the conventional way of doing things. But it may not be entirely what you are looking for.

Hope it helps nonetheless.

Happy coding!

maxtuzz
  • 1,945
  • 1
  • 10
  • 7