简体   繁体   English

如何访问动态局部变量

[英]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?我如何在本地 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根据情况,我想评估a<b 或 b<a

  • To accomplish this, I set two variables: compare1 and compare2为此,我设置了两个变量: compare1compare2
  • compare1 will reference either a or b and compare2 will reference the other compare1 将引用ab而 compare2 将引用另一个
  • Evaluate compare1 < compare2 or vice-versa评估compare1 < compare2或反之亦然

The following works perfectly with global variables.以下内容与全局变量完美配合。 However, I want a and b to be local.但是,我希望ab是本地的。

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.如果在上面我设置compare1=a ,那么每次a更改时我都必须重置compare1 Instead, I want to actually [look at/point to] the value of a .相反,我想实际 [查看/指向] a的值。

Use an object instead of a set of separate variables instead.使用 object 而不是一组单独的变量。 (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 返回,则可以全局引用它。

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.您可以使用eval完成此操作,但强烈建议不要使用 eval。 If you can wrangle your needs into David Dorward's recommendation, I'd do that:如果您可以根据 David Dorward 的建议来解决您的需求,我会这样做:

var myPet = 'dog';
var dog = 'fido';

eval("alert(" + myPet + ")");  // alerts "fido"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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