Create variable from string

0

Suppose I have:

var develop = 'confirmName1'

And I want to create a new variable from the value of the variable develop ("confirmName1"):

var 'confirmName1' = 'valorDaNovaVariavel'

alert(confrirmName); // Retornar: (String) valorDaNovaVariavel

In PHP I know, but apparently it does not work the same way in JavaScript .

    
asked by anonymous 19.10.2015 / 01:45

3 answers

4

There is a technique that you can do this. It's more or less like this:

var x = "nome"; 
eval("var " + x + " = 'Tonho';");
console.log("Valor da variável nome:", nome);

As you can see above, the function that makes the "magic" is called eval , however there are a number of restrictions that the use of function, especially when it comes to security ... < p>

  

Do not use eval unnecessarily! eval () is a dangerous function, which   executes the last code with the caller privileges. If you   run eval () with a string of characters that can be   affected by a malicious person, you may end up running code   malicious on the user's machine with the permissions of his   page / extension. Most importantly, third-party code can see   the scope in which eval () was called, which can lead to possible   attacks such as Function are not likely.

Learn the function completely here: link

### UPDATING ###

There is a "cleaner" and safer way to do this. See:

var x = "nome";
window[x] = "Tonho";
document.getElementById("resultado").textContent = "Valor da variável nome: " + nome;
<h3 id="resultado"></h3>

It is important to note that the dynamically created variable will be in the global scope of the application.

I hope I have helped.

    
19.10.2015 / 01:58
2

Here's a simple example:

var chave = 'valor';

window[chave] = 'valor';

document.write(valor); // valor = valor
    
20.10.2015 / 04:11
1

There are different ways to write this friend.

If you work with the concept of screens, I suggest something similar to this:

var tela = document.body;
var nameVar = "somar";
tela[nameVar] =  3.14 * 3.14;

//mais codigo e bla bla bla..
console.log("resultado", tela.somar);

//tambem pode recuperar o valor da var assim:
console.log("valor da var", tela[nameVar]);
    
20.10.2015 / 04:01