PDA

View Full Version : how to iterate through javascript variables?


htmlcssnewbie
02-07-2008, 11:05 AM
Say I have 3 javascript variables called Var1, Var2, and Var3, respectively. I want to pass each variable, one at a time, to a function called Ite. But I don't wish to call each variable in static fashion. Is there a way I can take advantage of the numerical nature of said variables and iterate from 1 to 3, calling these variables dynamically?

I'd like to do something like this:

function Ite(Var + num) // where Var + num is equal to the Var1, Var2 , or Var3
{
// do some stuff with the variable
}

thank you.

RysChwith
02-07-2008, 01:06 PM
I suppose you could use eval().for( var i = 1; i <= 3; i++ ) {
Ite( eval( "Var" + i );
}It's generally recommended to avoid eval() as much as possible, though. It'd be easier to store your values in an array or object rather than as separate variables.var values = [ var1, var2, var3 ];

for( var index in values ) {
Ite( values[ index ] );
}Rys

htmlcssnewbie
02-08-2008, 03:17 PM
I used eval but the object declaration is dully noted.

thanks.