Create dynamic variables in JavaScript

2

When I'm in PHP and have dynamic variables, ex: nomeVariavel1 , nomeVariavel2 , nomeVariavel3 , I use the following way to put in the bank:

$nomeVariavel = ${"nomeVarivavel".$contador}

How can I do exactly this in JavaScript? Passing as a parameter or in another way?

    
asked by anonymous 26.05.2017 / 18:23

2 answers

2

Actually what you wish neither is this is the good old array .

var nomeVariavel = [ 1, 2, 3];
for (var i = 0; i < 3; i++) {
    console.log(nomeVariavel[i]);
}

If you're doing it in PHP the way you posted it is doing so much wrong. And there it works just like JavaScript, just use an array .

    
26.05.2017 / 18:40
0

You can. However you have to remember that all variables without context, that is all variables that are not declared in an object, are of the context window ;

So,

   var a = 1;

is the same as

window.a = 1;

Then,

window.a = "hello world"
var nomeDaVariavel = "a";
alert(window[nomeDaVariavel]) // "hello world"

In ES6 the following is also possible:

let a = {[nomeDaVariavel]: "not hello world"};
console.log(a) // {"a": "not hello world"}
    
26.05.2017 / 18:32