How would I reference a dynamic local variable? This is easily accomplished with a global variable:
myPet = "dog";
console.log(window["myPet"]);
How would I do the same in a local scope?
Specifically what I'm trying to do:
myArray = [100,500,200,800];
a = 1; // Array index (operand 1)
b = 2; // Array index (operand 2)
Depending on the situation, I want to evaluate a<b or b<a
The following works perfectly with global variables. However, I want a and b to be local.
compare1 = "b"; compare2 = "a";
for(a=0; a<myArray.length; a++){
b = a+1;
while(b>=0 && myArray[window[compare1]] < myArray[[compare2]]){
/* Do something; */
b--;
}
}
If in the above I set compare1=a
then I would have to reset compare1 every time a changed. Instead, I want to actually [look at/point to] the value of a.
Use an object instead of a set of separate variables instead. (I can't think of a real world situation where you would want to use a dynamically named variable where it isn't part of a group of logically related ones).
var animals = { dog: "Rover", cat: "Flopsy", goldfish: "Killer" };
var which = 'dog';
alert(animals[which]);
You can accomplish this with eval
, however use of eval is highly discouraged. If you can wrangle your needs into David Dorward's recommendation, I'd do that:
var myPet = 'dog';
var dog = 'fido';
eval("alert(" + myPet + ")"); // alerts "fido"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With