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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Dynamic Variable Names 1

Status
Not open for further replies.

theKeyper

Technical User
Jun 11, 2003
79
AU

Hello,

I am trying to find an equivalent to PHP's "Variable Variables".

Baisically, if I have an unknown number of variables (stuff_1, stuff_2, stuff_3, etc...) and want to reference them using a loop, I might try the following:

Code:
for(i=1; i<=num_variables; i++)
{
	var tempstring = 'stuff_'+i;
	var string = tempstring;
}

With this code, of course the variable 'string' will simply equal 'stuff_1' instead of what I want which is the value of the variable 'stuff_1'.

In PHP I would use the following:

Code:
for($i=1; $i<=$num_variables; $i++)
{
	$tempstring = 'stuff_'.$i;
	$string = $$tempstring;
	//note the '$$'
}

Any help would be appreciated.

Thanks a lot.

-Keyper
 
depends on the scope of your variables... for global scope, here is one way:
Code:
for(i=1; i<=num_variables; i++)
{
    var string = window['stuff_'+i];
}

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
WOOOOHOOOOOOOOOOOOOOOOOOOOOOO!!!!!!!!!

Fantastic. Works well (In IE).

Just one question, do you have an idea of how cross-browser compatible this method is?

Thank you for your time and prompt response.

Regards,

Keyper
 
i would think it will work in any browser as it is all core js... can only test on IE6 and FF1.06 on WinXP pro though

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top