Create variable with the contents of another variable

0

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

Example:

var nome = "teste";

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

    
asked by anonymous 27.03.2017 / 23:29

1 answer

2

It is not a very common practice. The purpose 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 set the variable name dynamically, you can use 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
    
27.03.2017 / 23:36