?
Solved

Javascript Metaprogramming: Reference Variable Name by String?

Posted on 2011-05-09
17
Medium Priority
?
486 Views
Last Modified: 2012-05-11

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?)
0
Comment
Question by:jjsather
  • 9
  • 7
17 Comments
 
LVL 29

Expert Comment

by:Badotz
ID: 35725073
Why do you need to do this?
0
 
LVL 23

Accepted Solution

by:
cmalakar earned 1000 total points
ID: 35725666
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
 
LVL 29

Expert Comment

by:Badotz
ID: 35728826
Yeah, but eval is evil.

Still like to know why you need to do this?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:jjsather
ID: 35731634

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
 
LVL 29

Expert Comment

by:Badotz
ID: 35732035
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
 

Author Comment

by:jjsather
ID: 35732307

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
 
LVL 29

Expert Comment

by:Badotz
ID: 35732448
>>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
 

Author Comment

by:jjsather
ID: 35732551

>> 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
 
LVL 29

Assisted Solution

by:Badotz
Badotz earned 1000 total points
ID: 35733030
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
 

Author Comment

by:jjsather
ID: 35733424

Interesting. I'm not familiar with JSON, but this gives me more to think about. Thanks.
0
 
LVL 29

Expert Comment

by:Badotz
ID: 35739205
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
 

Author Comment

by:jjsather
ID: 35739362

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
 
LVL 29

Expert Comment

by:Badotz
ID: 35739655
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
 

Author Comment

by:jjsather
ID: 35739666

Ah, my bad. But I'm really ok if a mod steps in and alters it.
0
 
LVL 29

Expert Comment

by:Badotz
ID: 35739756
Fuhgeddaboudit ;-)

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

Author Comment

by:jjsather
ID: 35739809

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
 
LVL 29

Expert Comment

by:Badotz
ID: 35739997
JSON is JavaScript. Visit http://www.json.org for all things JSON.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question