Gary
Gary

Reputation: 13912

How to access dynamic local variables

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.

Upvotes: 5

Views: 1170

Answers (3)

Matt Ryan
Matt Ryan

Reputation: 1717

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);

Upvotes: 1

Quentin
Quentin

Reputation: 944204

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]);

Upvotes: 4

Matt Greer
Matt Greer

Reputation: 62057

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"

Upvotes: 1

Related Questions