Use dynamic variable names in JavaScript

2018-12-31 00:06发布

In PHP you can do amazing/horrendous things like this:

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

Is there any way of doing something like this with Javascript?

E.g. if I have a var name = 'the name of the variable'; can I get a reference to the variable with name name?

11条回答
步步皆殇っ
2楼-- · 2018-12-31 00:15

what they mean is no, you can't. there is no way to get it done. so it was possible you could do something like this

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

}

having a create function just like the one implemented in ECMAScript 5.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 00:18

eval() did not work in my tests. But adding new JavaScript code to the DOM tree is possible. So here is a function that adds a new variable:

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)
查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 00:19
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);

Try this...

查看更多
看风景的人
5楼-- · 2018-12-31 00:20

Since ECMA-/Javascript is all about Objects and Contexts (which, are also somekind of Object), every variable is stored in a such called Variable- (or in case of a Function, Activation Object).

So if you create variables like this:

var a = 1,
    b = 2,
    c = 3;

In the Global scope (= NO function context), you implicitly write those variables into the Global object (= window in a browser).

Those can get accessed by using the "dot" or "bracket" notation:

var name = window.a;

or

var name = window['a'];

This only works for the global object in this particular instance, because the Variable Object of the Global Object is the window object itself. Within the Context of a function, you don't have direct access to the Activation Object. For instance:

function foobar() {
   this.a = 1;
   this.b = 2;

   var name = window['a']; // === undefined
   alert(name);
   name = this['a']; // === 1
   alert(name);
}

new foobar();

new creates a new instance of a self-defined object (context). Without new the scope of the function would be also global (=window). This example would alert undefined and 1 respectively. If we would replace this.a = 1; this.b = 2 with:

var a = 1,
    b = 2;

Both alert outputs would be undefined. In that scenario, the variables a and b would get stored in the Activation Object from foobar, which we cannot access (of course we could access those directly by calling a and b).

查看更多
春风洒进眼中
6楼-- · 2018-12-31 00:25

This is an example :

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

Another example :

var myVariable = 'coco';
window[myVariable] = 'riko';

alert(coco); // display : riko

So, the value "coco" of myVariable becomes a variable coco.

Because all the variables in the global scope are properties of the Window object.

查看更多
梦寄多情
7楼-- · 2018-12-31 00:28

If you don't want to use a global object like window or global (node), you can try something like this:

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

console.log(obj['whatever']);
查看更多
登录 后发表回答