Field inside a variable dynamically?

Asked

Viewed 73 times

3

Follow the code below:

Javascript:

var img1 = false;
var img2 = true;

var img =  "img"+1;      //Resultado da variavel img é "img1".
                         //Como converter string para variável ?
                         //Exemplo: "img1" para img1

      if (img == false) //Errado ----> "img1" == false
      {                 //Certo -----> img1 == false ou seja false = false

      }

Some solution ?

  • 2

    Why don’t you use a array? It’s so much better and you don’t need this gambit..

  • 1

    You can give a concrete example of what you need to do?

  • 1

    Hi @bigown, can you believe

3 answers

4


If you want to insist on it you can do something like this:

var img1 = false;
var img2 = true;
var img = eval("img" + 1);
if (!img) console.log("ok");

But avoid using the eval(). The right thing to do is with a array:

var img = [false, true];
var img = img[0];
if (!img) console.log("ok");

I put in the Github for future reference.

Depending on the context another solution may be more appropriate.

I switched the img == false for !img if you have any doubt about it read that question.

  • You can also use string-casting - which is much safer: var img1 = 'hello'; var nome = "img"; console.log(window[''+nome+1]) (but more hammer still ;D)

  • 1

    @Moshmage tb, it’s all gambiarra, the array is the right solution.

  • Yes. It will be what he wants but not what he asked :P

  • Hi @bigown, helped me a lot. Array is very useful.

1

Instead of doing so uses array

vetor = new Array(false,true); //declarando e iniciando a array
var img = vetor[0]; //atribuindo o valor da posição 0 da array para a variavel 
if(img == false) {
    // ...
}

1

I suppose you need a code like that:

function foobar() {
   this.img1 = false;
   this.img2 = true;

   var img = this['img'.concat(1)];
   if (img == false) {
       alert("Falso!");
   }
   else {
       alert(img);
   }
}
new foobar();

If in a global context (outside of a function), you can exchange thisfor window. The function concat() will perform the concatenation, generating a1.

Browser other questions tagged

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