Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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.

like image 897
Gary Avatar asked Apr 29 '11 15:04

Gary


2 Answers

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]);
like image 118
Quentin Avatar answered Sep 29 '22 04:09

Quentin


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"
like image 30
Matt Greer Avatar answered Sep 29 '22 06:09

Matt Greer