user1880399
user1880399

Reputation: 3

Alternative to using eval to call slightly different function names?

My question was going to be how to do this at all but I came across eval which seems to work. I'm told eval is evil and the explanations for why went way over my head so my question is:

Is there anything wrong with using eval like this, or other ways to do it at all?

var condition1=false;
var condition2=true;
var condition3=false;
//etc

if (condition1){x = "1"}
else if (condition2){x = "2"}
else if (condition3){x = "3"};
//etc

var thing1= 11;
var thing2= 22;
var thing3= 33;
//etc

eval ("thing" + x)

Upvotes: 0

Views: 87

Answers (3)

tomsmeding
tomsmeding

Reputation: 926

Since you are building the strings to be eval()'ed yourself, there isn't any real danger involved. Things start getting nasty when you start eval()'ing user input.

I'd recommend arrays though. So you could just do this:

var conditions=[false, true, false];
for(var i=0;i<conditions.length;i++)
    if(condition[i])x=i+1; //i=0, 1, 2, ...; x=1, 2, 3, ...
eval("thing"+x+"()"); //don't forget the "()"!

Upvotes: 0

lostsource
lostsource

Reputation: 21830

You could have an object called things

var things = {
   "1": 11,
   "2": 22,
   "3": 33
}

Then you can refer to a thing with

things[x]

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

Probably the best solution would be to replace all of those variables with an array:

thing = [11, 22, 33 ...];

then you can just do :

thing[x];  // either change your code to zero indexed or subtract 1 here

If the variables are global, you could also do this:

window["thing"+x];

But ideally you would not want these to be global.

Upvotes: 5

Related Questions