在 JavaScript 中使用动态变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5117127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:44:15  来源:igfitidea点击:

Use dynamic variable names in JavaScript

javascriptdynamic-variables

提问by Finbarr

In PHP you can do amazing/horrendous things like this:

在 PHP 中,你可以做这样惊人/可怕的事情:

$a = 1;
$b = 2;
$c = 3;
$name = 'a';
echo $$name;
// prints 1

Is there any way of doing something like this with Javascript?

有没有办法用 Javascript 做这样的事情?

E.g. if I have a var name = 'the name of the variable';can I get a reference to the variable with name name?

例如,如果我有一个名称var name = 'the name of the variable';,我可以获得对变量的引用name吗?

回答by jAndy

Since ECMA-/Javascript is all about Objectsand Contexts(which, are also somekind of Object), every variable is stored in a such called Variable-(or in case of a Function, Activation Object).

由于 ECMA-/Javascript 都是关于Objectsand Contexts(它也是某种对象),所以每个变量都存储在一个称为Variable-(或者在函数的情况下,激活对象)中。

So if you create variables like this:

因此,如果您创建这样的变量:

var a = 1,
    b = 2,
    c = 3;

In the Global scope(= NO function context), you implicitly write those variables into the Global object(= windowin a browser).

全局范围内(= 无函数上下文),您将这些变量隐式写入全局对象(=window在浏览器中)。

Those can get accessed by using the "dot" or "bracket" notation:

这些可以通过使用“点”或“括号”符号来访问:

var name = window.a;

or

或者

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Objectof the Global Objectis the windowobject itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

这仅适用于在这种特定情况下的全局对象,因为变量对象中的全局对象window对象本身。在函数的 Context 中,您不能直接访问Activation Object。例如:

function foobar() {
   this.a = 1;
   this.b = 2;

   var name = window['a']; // === undefined
   alert(name);
   name = this['a']; // === 1
   alert(name);
}

new foobar();

newcreates a new instance of a self-defined object (context). Without newthe scope of the function would be also global(=window). This example would alert undefinedand 1respectively. If we would replace this.a = 1; this.b = 2with:

new创建自定义对象(上下文)的新实例。没有new函数的作用域也将是global(=window)。此示例将分别发出警报undefined1。如果我们将替换this.a = 1; this.b = 2为:

var a = 1,
    b = 2;

Both alert outputs would be undefined. In that scenario, the variables aand bwould get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling aand b).

两个警报输出都将是未定义的。在这种情况下,变量aandb将存储在 Activation Object from 中foobar,我们无法访问它(当然我们可以通过调用aand直接访问它们b)。

回答by erickb

evalis one option.

eval是一种选择。

var a = 1;
var name = 'a';

document.write(eval(name)); // 1

回答by JohnP

You can use the window object to get at it .

您可以使用 window 对象来获取它。

window['myVar']

windowhas a reference to all global variables and global functions you are using.

window具有对您正在使用的所有全局变量和全局函数的引用。

回答by Terry Lin

Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.

只是不知道一个糟糕的答案会得到这么多票。这是很简单的答案,但你让它变得复杂。

// If you want to get article_count
// var article_count = 1000;
var type = 'article';
this[type+'_count'] = 1000;  // in a function we use "this";
alert(article_count);

回答by amitchd

a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);

Try this...

尝试这个...

回答by Azodium

This is an example :

这是一个例子:

for(var i=0; i<=3; i++) {
    window['p'+i] = "hello " + i;
}

alert(p0); // hello 0
alert(p1); // hello 1
alert(p2); // hello 2
alert(p3); // hello 3

Another example :

另一个例子 :

var myVariable = 'coco';
window[myVariable] = 'riko';

alert(coco); // display : riko

So, the value "coco" of myVariablebecomes a variable coco.

因此,myVariable的值“ coco”变成了变量coco

Because all the variables in the global scope are properties of the Window object.

因为全局范围内的所有变量都是Window对象的属性。

回答by David Newcomb

In Javascript you can use the fact that all properties are key value pairs. jAndy already mentioned this but I don't think his answer show how it can be exploited.

在 Javascript 中,您可以使用所有属性都是键值对的事实。jAndy 已经提到了这一点,但我认为他的回答并没有说明它是如何被利用的。

Usually you are not trying to create a variable to hold a variable name but are trying to generate variable names and then use them. PHP does it with $$varnotation but Javascript doesn't need to because property keys are interchangeable with array keys.

通常,您不会尝试创建变量来保存变量名称,而是尝试生成变量名称然后使用它们。PHP 使用$$var符号来完成,但 Javascript 不需要,因为属性键可以与数组键互换。

var id = "abc";
var mine = {};
mine[id] = 123;
console.log(mine.abc);

gives 123. Usually you want to construct the variable which is why there is the indirection so you can also do it the other way around.

给出 123。通常你想构造变量,这就是为什么有间接性,所以你也可以反过来做。

var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);

回答by pery mimon

2019

2019年

TL;DR

TL; 博士

  • evaloperator can run string expression in the context it called and return variables from that context;
  • literal objecttheoretically can do that by write:{[varName]}, but it blocked by definition.
  • eval运算符可以在它调用的上下文中运行字符串表达式并从该上下文返回变量;
  • literal object理论上可以通过 write: 做到这一点{[varName]},但它被定义阻止。

So I come across this question and everyone here just play around without bringing a real solution. but @Axel Heider has a good approaching.

所以我遇到了这个问题,这里的每个人都在玩,没有带来真正的解决方案。但@Axel Heider 有一个很好的方法。

The solution is eval. almost most forgotten operator. ( think most one is with())

解决办法是eval。几乎最被遗忘的运算符。(认为​​大多数是with()

evaloperator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.

eval运算符可以在它调用的上下文中动态运行表达式。并返回该表达式的结果。我们可以使用它在函数的上下文中动态返回变量的值。

example:

例子:

function exmaple1(){
   var a = 1, b = 2, default = 3;
   var name = 'a';
   return eval(name)
}

example1() // return 1


function example2(option){
  var a = 1, b = 2, defaultValue = 3;

  switch(option){
    case 'a': name = 'a'; break;
    case 'b': name = 'b'; break;
    default: name = 'defaultValue';
  }
  return eval (name);
}

example2('a') // return 1
example2('b') // return 2
example2() // return 3

Note that I always write explicitly the expression evalwill run. To avoid unnecessary surprises in the code. evalis very strongBut I'm sure you know that already

请注意,我总是明确地编写表达式eval将运行。避免代码中出现不必要的意外。eval很强大但我相信你已经知道了

BTW, if it was legal we could use literal objectto capture the variable name and value, but we can't combine computed property names and property value shorthand, sadly, is invalid

顺便说一句,如果它是合法的,我们可以literal object用来捕获变量名称和值,但我们不能将计算属性名称和属性值速记结合起来,遗憾的是,这是无效的

functopn example( varName ){
    var var1 = 'foo', var2 ='bar'

    var capture = {[varName]}

}

example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`

回答by Brent Barbata

If you don't want to use a global object like window or global (node), you can try something like this:

如果你不想使用像 window 或 global(节点)这样的全局对象,你可以尝试这样的事情:

var obj = {};
obj['whatever'] = 'There\'s no need to store even more stuff in a global object.';

console.log(obj['whatever']);

回答by Talha

I needed to draw multiple FormData on the fly and object way worked well

我需要动态绘制多个 FormData 并且对象方式运行良好

var forms = {}

Then in my loops whereever i needed to create a form data i used

然后在我的循环中我需要创建我使用的表单数据

forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);