简体   繁体   中英

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 .

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM