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?
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?
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.
if selected is a global variable:
function resetVar(foo){
window[foo+"_id"] = 0;
}
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
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.