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

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

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

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


当前回答

Eval是一个选项。

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

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

其他回答

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

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

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

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

在ES6中使用let无效:

/*这不是工作*/ let t = "skyBlue", M = "黄金", B = "番茄"; Let color = window["b"]; console.log(颜色);

但是使用var是可行的

/*这个正在工作*/ var t = "skyBlue", M = "黄金", B = "番茄"; Let color = window["b"]; console.log(颜色);

我希望这对一些人有用。

最简单的解决方案:创建一个对象数组,每个对象都有两个字段(variableName,variableValue)

let allVariables = [];

for (let i = 0; i < 5; i++)
    allVariables.push({ variableName: 'variable' + i, variableValue: i * 10 });

for (let i = 0; i < allVariables.length; i++)
    console.log(allVariables[i].variableName + ' is ' + allVariables[i].variableValue);

输出:

variable0 is 0
variable1 is 10
variable2 is 20
variable3 is 30
variable4 is 40

console.log(allVariables) json :

 [
    {
        "variableName": "variable0",
        "variableValue": 0
    },
    {
        "variableName": "variable1",
        "variableValue": 10
    },
    {
        "variableName": "variable2",
        "variableValue": 20
    },
    {
        "variableName": "variable3",
        "variableValue": 30
    },
    {
        "variableName": "variable4",
        "variableValue": 40
    }
]

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

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

这是一个例子:

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对象的属性。