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

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

有什么方法可以用Javascript做这样的事情吗?

例如,如果我有一个var name = '变量的名称';我可以得到一个引用的变量与名称?


当前回答

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

试试这个…

其他回答

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

window['myVar']

Window有一个对你正在使用的所有全局变量和全局函数的引用。

Eval是一个选项。

var a = 1; var name = 'a'; document.write (eval ());/ / 1

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

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)

只是不知道为什么一个糟糕的答案能得到这么多票。这个答案很简单,但你把它弄复杂了。

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

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

请看下面的代码片段:

//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"

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