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));}
eval and understand those risks.evaledeval is never the answer, we shouldn't encourage to use eval without any explanation, OP should be aware of the security implications.eval is not good solution here.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
const strings = {s0: "Hello", s1: "Bye"}; console.log(strings["s" + i]);, or an array.