Create dynamic variables in Javascript

Asked

Viewed 429 times

2

When I’m in PHP and has dynamic variables, e.g.: nomeVariavel1,nomeVariavel2, nomeVariavel3, I use it as follows to place on the bench:

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

How can I do exactly that in Javascript? Passing as parameter or otherwise?

  • 1

    Possible duplicate of Dynamically create variable

  • Possible duplicate of https://answall.com/questions/122604/howto create a variable-din%C3%A2mica

  • I think there might be a duplicate but I don’t think these are, at least not for something so simple.

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

2 answers

3

Actually what you want is not what is good is old array.

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

I put in the Github for future reference.

If you are doing it in PHP in the posted way you are doing it very wrong. And there it works like Javascript, just use one array.

  • Actually I need to close windows created with window.open, then var mywindow = window.open(...) . Then I need to take this variable as parameter. And a variable , if I pass function ("mywindow"). this parameter cannot do a mywindow.close() of course. I wanted a way to do this

  • 2

    Your question doesn’t talk about, I answered what you asked about.

  • 2

    @Rodrigoluan just pass the direct reference of mywindow as parameter. Pass a string and want to access the string doesn’t make any sense in this case. As the bigown said: it’s doing very wrong.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.