Javascript Metaprogramming: Reference Variable Name by String?


I know Javascript can do meta-programming, but I'm not sure to what extent. This is a silly example, but if I have a string with a value, can I check if there's an existing variable by that name and get it's value? For instance...

var my_num = 42;
var my_other_num = 52;
var var_name = "my_num";

By going through var_name, is there a way to reference the value of my_num to return 42? (So that later on, if var_name = "my_other_num", it would return 52 instead?)
jjsatherAsked:
Who is Participating?
 
cmalakarCommented:
eval(var_name);

Will give the value as 42, if var_name value is set to my_num and if it is set to my_other_num it will give the value 52.
0
 
BadotzCommented:
Why do you need to do this?
0
 
BadotzCommented:
Yeah, but eval is evil.

Still like to know why you need to do this?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
jjsatherAuthor Commented:

Thanks for the solution. If eval is evil, I'll take different suggestions. Does it not work the same in different browsers? Otherwise, why is it evil?

As for why, I'm thinking of making an engine based off a data file that needs extensive "if" conditions. This way a person can edit the data file to change the execution logic without changing any code. This assumes whoever changes the data has a list of all relevant code variables, so the variable names in the data file will match.

Make sense?
0
 
BadotzCommented:
Not really...

If you control the data file, then won't you be able to map "fieldX" to "varX" no matter where "fieldX" appears in the data file?
0
 
jjsatherAuthor Commented:

Let me throw out an example...

In the code (where the variables will have very meaningful names)...

var_a;
var_b;
var_c;
var_d;
var_e;

[engine that reads data and works with input from user based off data and how vars are treated]



In the data file, everything before the # is evaluated, and everything after the second # is assigned. The first true condition met outputs a text response and optionally changes other variables...

var_a=1#Text response A.#
var_b=1#Text response B.#
var_c=1#Text response C.#
var_a=0&var_c=1#Text response D.#var_b=1
var_c=1&var_b=0#Text response E.#var_a=0;var_c=2
var_a=2||var_c=2#Text response F.#var_d=1

etc.


This allows the user, who has no code experience, to edit the data and add lines to change the execution logic and response to the user. So later if they decide when a, b, and e are 1, they want a new response and a change to c, so they add...

var_a=1&var_b=1&var_e=1#Textual response G.#var_c=3

Now I never claimed this was the best way, but knowing there will be 100's of such conditional statements, an ever-changing data file and non-changing engine to process it seemed fairly straightforward to me, but I'll take suggestions.
0
 
BadotzCommented:
>>In the data file, everything before the # is evaluated

Evaluated in JavaScript?

>>and everything after the second # is assigned

Assigned to what?

>>This allows the user, who has no code experience, to edit the data

If I presented such a datafile to most of my users, they would look at it like it was in a foreign language.

Sorry, but I don't grok the Big Picture. If you can give an actual example of a datafile, then I can have another go at it. Otherwise it just seems like a lot of unnecessary work.

0
 
jjsatherAuthor Commented:

>> Evaluated in JavaScript?

Yes

>> Assigned to what?

The matching variable names. That's why they have to match.

>> Sorry, but I don't grok the Big Picture...

Oh, well. Like I said, I'm not sure it's the best way, but it seems to allow lots of flexibility without tons of "if" statements everywhere.

Think of it this way: Remember those old DOS text adventures? It'd be like an engine for those. Meaning, if you have a certain item and/or you are in a certain location, the engine responds differently to your commands and changes variables accordingly. It also allows different data files to present an entirely different adventure, even though you use the same code engine.
0
 
BadotzCommented:
So there is an initial variable (var_a = 1) and some kind of message. OK.

Or there is a series of variables (var_a=0&var_c=1), some kind of message, and a result variable (var_b=1).

How, where and why the values of these variables change is a mystery. If var_a is equal to 1, how does it then become equal to 0?

Presumably, the Engine (you) know the answers to these questions.

In answer to your original question, yes, eval will work, but a malicious datafile could compromise the security of your site, since eval will try to evaluate anything.

You might consider a JSON approach, where you read the datafile and create properties based upon the content:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script text="javascript">

    function page_load() {
        
        var J = {}; // JSON instead of eval
        var cmd = "";
        
        J["item_1"] = { "elem":"var_a", "init":1, "text":"Text response A" };
        J["item_2"] = { "elem":"var_b", "init":1, "text":"Text response B" };
        J["item_3"] = { "elem":"var_c", "init":1, "text":"Text response C" };
        J["item_4"] = { "elem":"var_d", "init":0, "text":"Text response C" };
        
        J["state_1"] = { "true":"var_a == 0 && var_c == 1", "text":"Text response D", "result":"var_b=1" };
        J["state_2"] = { "true":"var_c == 1 && var_b == 0", "text":"Text response E", "result":"var_c=2" };
        J["state_3"] = { "true":"var_a == 2 || var_c == 2", "text":"Text response F", "result":"var_d=1" };
        
        // Investigation
        alert(J.state_1.result + "\t");
        
        // Since you know the content of "J" is good, you can use "eval" to test and modifiy it
        
        cmd = J.item_2.elem + "=" +  J.item_2.init;
        alert(cmd + "\t");
        
        cmd = J.item_2.elem + "=" +  J.state_2.text;
        alert(cmd + "\t");
        
        alert(J.item_4.elem + "=" + J.item_4.init + "\t"); // Initial value
        J.item_4.init = eval (J.state_3.result); // Change value
        alert(J.item_4.elem + "=" + J.item_4.init + "\t"); // Prove it has changed
    }

    window.onload = page_load;

</script>
</head>
<body>
</body>
</html>

Open in new window

0
 
jjsatherAuthor Commented:

Interesting. I'm not familiar with JSON, but this gives me more to think about. Thanks.
0
 
BadotzCommented:
So what did you decide to do?





BTW: a 50-50 point split for all the care and love I bestowed upon you? Hardly seems fair, eh?
0
 
jjsatherAuthor Commented:

Yeah, I didn't know how to divide it up. Because if someone is looking for the answer to the question, then eval is the answer, which Badotz offered. But for me specifically, you were most helpful as I change my approach, but I'm not sure how yet.

Can a moderator step in and change the scores as they think it should be?
0
 
BadotzCommented:
Nah, I was just just whinging...You'll do better next time ;-)

The points don't affect the searching, only the status of the Experts in question.
0
 
jjsatherAuthor Commented:

Ah, my bad. But I'm really ok if a mod steps in and alters it.
0
 
BadotzCommented:
Fuhgeddaboudit ;-)

So what did you decide to do? Just use eval or something more flexible?
0
 
jjsatherAuthor Commented:

I'll avoid eval and at least check out JSON. Otherwise, your post made me wonder if there's any wisdom in writing a program that processes a data file and generates the desired code, which can be pasted and compiled into the main program. That sounds like what you said JSON does, but not sure how it all fits with javascript.
0
 
BadotzCommented:
JSON is JavaScript. Visit http://www.json.org for all things JSON.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.