Lets say I have a variables var s0="Hello",var s1="Bye"
and I have
for(var i = 0; i < 1; i++) {console.log("s"+i);}
How would I access those strings(s0 and s1) to print out?
Lets say I have a variables var s0="Hello",var s1="Bye"
and I have
for(var i = 0; i < 1; i++) {console.log("s"+i);}
How would I access those strings(s0 and s1) to print out?
For global level variables:
for(var i = 0; i < 1; i++) {console.log(window["s"+i]);}
For local variables:
for(var i = 0; i < 1; i++) {console.log(eval("s"+i));}
If you are planning on accessing a list of variables in that way you should probably store them in an array like this
s = ["Hello", "Bye"];
for(var i = 0; i < 1; i++) {console.log(s[i]);}
This is the proper way and you should probably stop reading here.
But.... because javascript is weird it is possible to access "global" variables directly attached to the window via strings like this
s0 = "Hello"
s1 = "Bye"
for(var i = 0; i < 1; i++) {console.log(window["s"+i]);}
Essentially you are accessing the variables on window via window["s0"]
. The "s" + i
statement turns into either "s0"
or "s1"
because again, javascript is weird, and adding a number to a string results in a string.
Do not do this ever. Stick to original the method above
You can use eval function, to execute a code you construct dynamically like a string:
for(var i=0; i<=1; i++) { eval("console.log(s" + i + ")"); }