Create variable with other variable content

Asked

Viewed 533 times

0

I need to create a variable but its name has to be the content of another already created.

Example:

var nome = "teste";

Now using the value of the name variable that is "test" need to automatically create a test variable

1 answer

2

It is not a very common practice. The goal of defining a variable is to be able to use its content later. If you create this variable dynamically, you will need to access your content dynamically as well, which is not very practical.

What you can do is create a map dynamically.

For example.

var nome = 'teste';
var mapa = {};

mapa[nome] = 123;

console.log(mapa);
// Retorna { teste: 123 }

If you really want to dynamically define the variable name, you can use the eval, but it’s a bad practice.

var nome = 'teste';
texto = nome + ' = ' + '123';

// Como estamos gerando o nome dinamicamente, precisamos
// adicionar um try catch para capturar possíveis nomes inválidos
try {
  eval(texto);
} catch (err) {
  console.log(err);
}

console.log(teste);
// Retorna 123
  • Do not forget to put a Try catch on Eval if it is not a valid variable name.

  • @Mathias opa, well remembered :)

Browser other questions tagged

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