Field within a variable dynamically?

2

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

      }

Any solution?

    
asked by anonymous 25.11.2016 / 20:34

3 answers

2

If you want to insist on this 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 eval() . The correct thing is to do with an array :

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

Depending on the context, another solution may be more appropriate.

I've changed img == false'' por ! img 'if in doubt about this read this question .

    
25.11.2016 / 20:47
1

I suppose you need code like this:

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 you are in a global context (out of a function ), you can switch this to window . The concat() function will concatenate, generating a1 .

    
25.11.2016 / 20:46
1

Instead of doing so using 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) {
    // ...
}
    
25.11.2016 / 20:43