Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic variable name 1

Status
Not open for further replies.

chebbi

Programmer
Joined
Feb 6, 2002
Messages
98
Location
IN
Is it possible to generate dynamic variable names in javascript.
I want to be able to generate variables like v1,v2,v3 etc and the numbers 1,2,3 in the above variable names should come dynamically from a loop like

for (i=0;i<=3;i++)
{
//i need a substitute for the below line
var &quot;v&quot;+i=somevalue;
}

Is this possible to do in javascript? I tried
var eval(&quot;v&quot;+i)=somevalue; but that didnt work.
Badrinath Chebbi
 
Use an array, and it'll do what it looks like you're trying without the awkward name manipulation.
 
Yes, it's possible, but you need to do differently. This might work:
Code:
eval(&quot;var v&quot;+i+&quot;=&quot;+someValue+&quot;;&quot;);
It's not normally done with js variables though. Like trollacious said, you would normally use an array for that. It's normally done with form variables like this:
Code:
var theFld = eval(&quot;document.formname.fld&quot;+i);
theFld.value = someValue;
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Thanks tracey. I'll try your suggestion. By the way i cannot use arrays as a substitute for this approach due to some design problems. Badrinath Chebbi
 
There's also a way to achieve the same without doing so much annoying string concatenation:[COLOR=aa0000]
Code:
window[&quot;v&quot; + i] = somevalue;
[/color]

That's because all global variables are properties of the [COLOR=aa0000]
Code:
window
[/color].

And, if you didn't know, it's an alternative way to access properties of objects by name. Check this out:
[COLOR=aa0000]
Code:
alert(window[&quot;document&quot;][&quot;location&quot;][&quot;href&quot;]);
[/color]
That's practically the same as saying:
[COLOR=aa0000]
Code:
alert(window.document.location.href);
[/color]
Code:
- UNIMENT
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top