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?

mrwadepro
  • 229
  • 1
  • 6
  • 16
  • 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. – Sebastian Simon May 14 '18 at 23:27

3 Answers3

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));}
Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35
  • 1
    Be careful with using `eval` and understand those risks. – Kurt May 14 '18 at 23:28
  • @Kurt the question is not about what is the safest way of doing it. – Karen Grigoryan May 14 '18 at 23:29
  • Ya, sorry. I missed the "global level variables" part of your answer so I removed that from my comment. – Kurt May 14 '18 at 23:30
  • 1
    @Kurt: There is no risk here since there is no user input being `eval`ed – Felix Kling May 14 '18 at 23:31
  • 1
    `eval` is never the answer, we shouldn't encourage to use `eval` without any explanation, OP should be aware of the security implications. – Marcos Casagrande May 14 '18 at 23:31
  • @MarcosCasagrande: *"`eval` is never the answer, "* I disagree. If you have JavaScript as input then `eval` (or something similar) is exactly what you want. However, unfortunately it is also used when there are better alternatives. It's also not always a security risk. It very much depends on the input that it is provided. – Felix Kling May 14 '18 at 23:34
  • @FelixKling `eval` is almost never the answer sounds better? But it's definately not a good answer for this question if you ask me. Either using the `window` object for globally defined variables, or using an object for local scope should be the recommended approach. – Marcos Casagrande May 14 '18 at 23:37
  • 1
    @MarcosCasagrande: Yes, agreed, `eval` is not good solution here. – Felix Kling May 14 '18 at 23:38
  • @MarcosCasagrande `Eval` is a code generation construction on par with `Function` constructor, they all have their use cases. There is nothing specifically dangerous about eval which should discourage one from using it, the same way as man-in-the-middle attacks don't discourage you from working with json in your code. Usually the real problem lies deeper. Code injection as outlined earlier is only possible if you work with the user input and don't do any sanitization, which is already a problem and getting rid of eval won't save you. – Karen Grigoryan May 14 '18 at 23:48
  • `eval` is really slow, it shouldn't be used for this, your answer is bad, since you're telling someone who know less than you, to use it without further explanation. – Marcos Casagrande May 14 '18 at 23:52
  • @MarcosCasagrande and the question is still not about what is the recommended way of storing strings for further dynamic evaluation. It is clearly about given this, how can I evaluate that. In which case eval is the most logical answer for non-global code. – Karen Grigoryan May 14 '18 at 23:52
  • The most logical & best answer, is to use an object for non global code. – Marcos Casagrande May 14 '18 at 23:53
  • @MarcosCasagrande context matters, I am not making judgements on OP's level of knowledge, I am basing my answer on the question, which clearly stated a precondition. And I give a solution based on that condition, which is absolutely technically suitable. Now is it good or bad is debatable. I think using eval for code generation purposes is totally valid, since it's been used forever and is still being used in the most sophisticated software development pieces like devtools. There was no notion to give the most performant/concise or even a question on what is the best way to structure the code. – Karen Grigoryan May 15 '18 at 00:02
  • @MarcosCasagrande regarding slow, it's not an argument, `map` is slower than `for()`, so should `map` be discouraged for usage? No. Because it depends on specific case what do you want to achieve and fine-tune. If you have a hot loop with 1000 000 cycles then of course don't use `eval` for generating vars en-mass, but in all other cases what's the problem? I am not saying you should only use that, I am just saying it's an option, shouldn't be blindly discouraged. – Karen Grigoryan May 15 '18 at 00:06
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

Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
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 + ")"); }
SalvadorGomez
  • 552
  • 4
  • 15