1

I got this code:

var currentsettimevarstring = 'settimevar' + c, 
currentsettimevar = currentsettimevarstring;

I want the output of currentsettimevarstring to be settimevar1 (or 2, 3, 4, etc) and the output of currentsettimevar to be the content of the variable settimevar1

How can this be done?

cmplieger
  • 7,155
  • 15
  • 55
  • 83
  • I suppose `eval`...but that's not a good idea. Why are you doing this? – tymeJV Apr 09 '14 at 18:18
  • This is a reasonable thing for, say, a code obfuscation contest or to practice some sort of metaprogramming. But you should be aware that this is not a reasonable thing to do in "normal" code. There are much, much better ways to accomplish... whatever it is you're trying to accomplish. – Ian Henry Apr 09 '14 at 18:38

4 Answers4

1

You should be able to use eval for this: var currentsettimevar = eval('sitetimevar' + c)

Keep in mind that using eval can be a bad idea.

Community
  • 1
  • 1
Justin Self
  • 6,137
  • 3
  • 33
  • 48
1

If the settimevar variables are global variables, you can reference them on the window object using the currentsettimevarstring as the key:

var currentsettimevar = window[currentsettimevarstring];

If they are not global variables, then you may want to consider storing them in an array or as properties of an object that you can reference by key.

var settimevar = ['a', 'b', 'c', 'd', 'e'];
var c = 5;
var currentsettimevar = settimevar[c - 1];
mellamokb
  • 56,094
  • 12
  • 110
  • 136
0

This is a duplicate.

Basically, javascript has a global scope you can access with the 'window' variable, and index the defined variables like you would any other collection.

var c = 5;
var settimevar5 = "Some String";
var currentsettimevarstring = 'settimevar' + c, 
var currentsettimevar = window[currentsettimevarstring];

currentsettimevar should now be "Some String"

Community
  • 1
  • 1
Joe
  • 308
  • 1
  • 7
  • Only works IF they are in the global scope... or if they variables or members off of another object... which there is no indication that is the case. I don't see how this is a duplicate question. – Justin Self Apr 09 '14 at 18:49
  • @justnS: Because it's about the same problem, how to get the value of a variable, given the variable's name as a string. – Felix Kling Apr 09 '14 at 18:57
  • Indeed. I did say this works for the global scope as well as any other collection. If you were inside a function, closure, whatever, then you can use the this[] instead of window[] and achieve the same thing. – Joe Apr 10 '14 at 20:59
0

Use arrays instead:

var settimevar = ['value1', 'value2', 'value3'],
    c = 0, /* for example */
    currentsettimevar = settimevar[c];
Oriol
  • 274,082
  • 63
  • 437
  • 513