2

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?

1
  • 2
    You never need unknown variable names. Please use an object instead: const strings = {s0: "Hello", s1: "Bye"}; console.log(strings["s" + i]);, or an array. Commented May 14, 2018 at 23:27

3 Answers 3

3

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));}
Sign up to request clarification or add additional context in comments.

14 Comments

Be careful with using eval and understand those risks.
@Kurt the question is not about what is the safest way of doing it.
@Kurt: There is no risk here since there is no user input being evaled
eval is never the answer, we shouldn't encourage to use eval without any explanation, OP should be aware of the security implications.
@MarcosCasagrande: Yes, agreed, eval is not good solution here.
|
2

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

Comments

0

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 + ")"); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.