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

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

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

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


当前回答

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

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

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

其他回答

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

请看下面的代码片段:

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

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

这是一个例子:

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

这是一个纯javascript解决方案,它不依赖于运行时环境的全局this。使用对象解构实现简单。

const dynamicVar = (nameValue, value) => {
    const dynamicVarObj = {
        [nameValue]: value
    }
    return dynamicVarObj;
}

const nameToUse = "myVar";
const value = 55;

const { myVar } = dynamicVar(nameToUse, value);

console.log(myVar); // prints 55

最简单的解决方案:创建一个对象数组,每个对象都有两个字段(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
    }
]

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

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