/    Sign up×
Community /Pin to ProfileBookmark

Using eval to determine the value of a var

I’ve run into a block… I need to retrieve the value of a variable, but I need to dynamically get the value of the variable.

Take this for example.

CODE:
——————————————————————–

var mMenu1 = “Menu 1”;
var mMenu2 = “Menu 2”;
var mMenu3 = “Menu 3”;
var flag = true;

//Now I want to use a loop to figure out what each of the values are… Now in all reality, I won’t know what the number goes up to, so I’ll have to use a while loop…

var x = 0;
while(flag) {
x++;
//When x hits 4, eval can’t find the var and kills my code… What I really need to know is if there’s some condition I can run to check whether that var exists before running the eval statement or if the eval statement returns some “undefined” thing if the var doesn’t exist.

if (somecondition) {
mTest = eval(“mMenu”+x);
}
else {
flag = false;
}

}
——————————————————————-

Any help would be appreciated, thanks ?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@fredmvFeb 12.2004 — Welcome to the forums.<script type="text/javascript">
//<![CDATA[
var foo1 = 'var1', foo2 = 'var2', foo3 = 'var3', i = 0;

<i> </i>while(i++ &lt; 3) alert('foo' + i + ' = ' + window['foo' + i]);
//]]&gt;
&lt;/script&gt;
×

Success!

Help @Electricalfury spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...