5

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

  • To accomplish this, I set two variables: compare1 and compare2
  • compare1 will reference either a or b and compare2 will reference the other
  • Evaluate compare1 < compare2 or vice-versa

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.

Gary
  • 13,303
  • 18
  • 49
  • 71

3 Answers3

4

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]);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This answer accomplishes exactly what I'm trying to do, thank you. For argument's sake though, is it possible to dynamically reference local variables? What would they be attached to (as in global are attached to 'window')? – Gary Oct 02 '11 at 01:33
  • 2
    Local variables are added to the "activation object" that is created for each function that you enter. As far as I am aware, there is no way to access the activation object to dynamically access its members. --- Dmitry Soshnikov has done a lot of exploration and good writing on the internals of ECMAScript. Here's an article he wrote that discusses how the AO works. Reading this should put you on the path to determining whether there is a way or not: http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#variable-object-in-function-context – Jason LeBrun Oct 02 '11 at 01:46
1

you can reference a local variable globally if it is returned by a function.

function dog(name) {

  var local = name;

  return local;

}

myPet = dog('spike');

alert(myPet);
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Matt Ryan
  • 1,717
  • 2
  • 20
  • 30
1

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"
Matt Greer
  • 60,826
  • 17
  • 123
  • 123
  • Thanks Matt, eval is the only way I could figure to do this but I was trying to avoid it. – Gary Apr 29 '11 at 15:42