名的另一个变量

问题描述:

字符串值之后变量假设可以有两个变量名的另一个变量

var variable = "paypay"; 
var value = "this is the value of paypay!"; 

通过上面的信息,有没有一种方法,使paypay = "this is the value of paypay!"

你可以把它在字典:

var obj = {}; 
obj[variable] = value; 

然后obj.paypay是一个变量,它现在是"this is the value of payday!"

+0

'window [variable] = value;'也可以在不需要对象的情况下工作。所以你可以使用'paypay'而不用'obj.'paypay – NewToJS

var variable = "paypay"; 
var value = "this is the value of paypay!"; 

一些可能性

var parent = {}; 

parent.variable = value; // this is the value of paypay! 
parent[variable] = value; // this is the value of paypay! 
parent["paypay"] = value; // this is the value of paypay! 
parent.paypay = value; // this is the value of paypay! 
var "paypay"  = value; // error Unexpected string 
var paypay  = value; // this is the value of paypay! 
+1

为什么不'var paypay'呢?这里的“父母”有什么意义? –

假设你正确作用域为关闭或以其他方式...那么你就可以欺骗和还挺使用“本”;

实施例:

this[variable] = value; 
console.log(variable); 
+0

但是,我认真考虑ergonaut的建议,并将其填充到一个对象中,如果您处于当前的Javascript舒适级别,则可能比使用“this”更安全。 –

eval("var " + variable + "=" + value); 

即即使使用eval()函数并不总是建议的解决方案。

+0

''var''后面缺少空格 – Lucius

+0

谢谢,更正! –