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

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

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

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


当前回答

使用Object也很棒。

var a=123
var b=234
var temp = {"a":a,"b":b}
console.log(temp["a"],temp["b"]);

其他回答

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

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中实现的那样。

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

试试这个…

我需要绘制多个FormData在飞行和对象的方式工作得很好

var forms = {}

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

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

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

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