391

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

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

Is there any way of doing something like this with 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?

4

17 回答 17

390

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

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

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

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

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

var name = window.a;

或者

var name = window['a'];

这仅适用于此特定实例中的全局对象,因为全局对象的变量对象就是对象本身。在函数的上下文中,您无法直接访问Activation Object。例如:window

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

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

new foobar();

new创建自定义对象(上下文)的新实例。没有new函数的范围也将是global(=window)。这个例子会分别提醒undefined1。如果我们将替换this.a = 1; this.b = 2为:

var a = 1,
    b = 2;

两个警报输出都未定义。在那种情况下,变量ab将被存储在foobar我们无法访问的激活对象中(当然我们可以通过调用a和直接访问它们b)。

于 2011-02-25T12:23:47.723 回答
161

eval是一种选择。

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

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

警告:请注意,eval()如果您不知道自己在做什么,不建议使用该功能,因为它会带来多个安全问题。除非绝对必要,否则请使用其他东西。有关更多信息,请参阅评估的 MDN 页面。

于 2011-02-25T12:22:34.460 回答
98

You can use the window object to get at it .

window['myVar']

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

于 2011-02-25T12:21:56.863 回答
55

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

// 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);
于 2015-01-21T09:11:26.087 回答
32

这是一个例子:

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

另一个例子 :

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

alert(coco); // display : riko

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

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

于 2015-01-24T20:55:29.053 回答
28
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);

尝试这个...

于 2011-02-25T12:23:58.840 回答
19

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

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

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

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

var mine = {};
mine.abc = 123;
console.log(mine["a"+"bc"]);
于 2014-11-27T02:42:47.817 回答
7

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

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

console.log(obj['whatever']);
于 2015-01-30T00:06:51.860 回答
7

2019

TL;博士

  • eval运算符可以在它调用的上下文中运行字符串表达式并从该上下文返回变量;
  • literal object理论上可以通过 write: 来做到这一点{[varName]},但它被定义阻止了。

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

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

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

例子:

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

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

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

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

    var capture = {[varName]}

}

example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`
于 2019-01-04T19:08:26.327 回答
6

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

var forms = {}

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

forms["formdata"+counter]=new FormData();
forms["formdata"+counter].append(var_name, var_value);
于 2017-09-17T23:21:21.837 回答
3

对于需要导出动态命名变量的人来说,这是一种替代方法

export {
  [someVariable]: 'some value',
  [anotherVariable]: 'another value',
}

// then.... import from another file like this:
import * as vars from './some-file'

另一种选择是简单地创建一个对象,其键是动态命名的

const vars = { [someVariable]: 1, [otherVariable]: 2 };

// consume it like this
vars[someVariable];
于 2019-05-23T18:09:41.187 回答
1

虽然这有一个公认的答案,但我想补充一点:

在 ES6 中使用let 不起作用

/*this is NOT working*/
let t = "skyBlue",
    m = "gold",
    b = "tomato";

let color = window["b"];
console.log(color);

但是使用var 作品

/*this IS working*/
var t = "skyBlue",
    m = "gold",
    b = "tomato";

let color = window["b"];
console.log(color);

我希望这可能对某些人有用。

于 2019-03-23T09:36:34.193 回答
1

使用对象也很棒。

var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);
于 2019-03-20T07:58:02.297 回答
-1

eval() 在我的测试中不起作用。但是向 DOM 树中添加新的 JavaScript 代码是可能的。所以这是一个添加新变量的函数:

function createVariable(varName,varContent)
{
  var scriptStr = "var "+varName+"= \""+varContent+"\""

  var node_scriptCode = document.createTextNode( scriptStr )
  var node_script = document.createElement("script");
  node_script.type = "text/javascript"
  node_script.appendChild(node_scriptCode);

  var node_head = document.getElementsByTagName("head")[0]
  node_head.appendChild(node_script);
}

createVariable("dynamicVar", "some content")
console.log(dynamicVar)
于 2014-10-05T22:50:13.707 回答
-1

他们的意思是不,你不能。没有办法完成它。所以你可以做这样的事情

function create(obj, const){
// where obj is an object and const is a variable name
function const () {}

const.prototype.myProperty = property_value;
// .. more prototype

return new const();

}

拥有一个创建函数,就像在 ECMAScript 5 中实现的那样。

于 2012-11-24T05:29:27.540 回答
-1

这将完全按照您在 php 中所做的操作:

var a = 1;
var b = 2;
var ccc = 3;
var name = 'a';
console.log( window[name] ); // 1
于 2020-09-16T11:30:01.557 回答
-1

最好使用创建命名空间并在其中声明一个变量,而不是将其添加到全局对象中。我们还可以创建一个函数来获取和设置值

请参见下面的代码片段:

//creating a namespace in which all the variables will be defined.
var myObjects={};

//function that will set the name property in the myObjects namespace
function setName(val){
  myObjects.Name=val;
}

//function that will return the name property in the myObjects namespace
function getName(){
  return myObjects.Name;
}

//now we can use it like:
  setName("kevin");
  var x = getName();
  var y = x;
  console.log(y)  //"kevin"
  var z = "y";
  console.log(z); //"y"
  console.log(eval(z)); //"kevin"

以这种类似的方式,我们可以声明和使用多个变量。虽然这会增加代码行但代码会更健壮且不易出错。

于 2020-09-01T17:16:15.720 回答