0

Possible Duplicate:
Javascript Variable Variables

Please take a look at code below

var selected_id=1;   
resetVar("selected");

function resetVar(foo){
 foo+"_id"=0; // I want to set selected_id into 0
}​​​​​

Is that possible? Any suggestion?

Community
  • 1
  • 1
heron
  • 3,611
  • 25
  • 80
  • 148
  • 1
    It's not possible in that exact way, but you can create property names of objects that way. You can also, of course, use an array, which is naturally numerically indexed. – Pointy Apr 25 '12 at 20:56
  • Asking for a solution to a high level problem is often better than asking for us to solve the last 10% of your proposed solution that doesn't make a lot of sense. – Ed S. Apr 25 '12 at 22:07

4 Answers4

8

If your variables are global variables, then they are implicitly properties of the window object and you can reference them as properties of the window object like this:

function resetVar(foo){
    window[foo + "_id"] = 0; 
}​​​​​

var selected_id = 1;   
resetVar("selected");

If your variables are not global variables, then you will need to make them properties of some known object so that you can use this same technique.

In general, this is usually a bad programming idea and we often see this question where there are better ways to handle the situation. You don't disclose what the overall situation is so we can't advise very specifically, but you should usually be using properties on a known object directly or you should be using an array to hold several related values in the array or you should just be referencing the variable directly.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
3

if selected is a global variable:

function resetVar(foo){
    window[foo+"_id"] = 0;
}​​​​​
voigtan
  • 8,953
  • 2
  • 29
  • 30
2

You can invoke functions using square bracket notation on the object which owns the method (in your case, the global, window object).

window['selected_id'] = value

JonnyReeves
  • 6,119
  • 2
  • 26
  • 28
1

This is a "solution" often proposed by beginners (which is not a bad thing, everyone starts somewhere). The answer is; don't do that, use an array (or some other collection).

Using variable names to determine program logic is a terrible idea that will inevitably lead to messy, unmaintainable code. Changing the name of a varibale should not change your program's logic. Instead, group obbjects into a collection, using a key into the collection if needed, or simply the index.

Ed S.
  • 122,712
  • 22
  • 185
  • 265