0

I am doing the following:

var var1 = 58;

for(var i=0;i<10;i++){
 if(("var"+i) == 58) {
 console.log("they are equal");
 }
}

Could somebody explain me why ("var" + i) is not getting the value 58?

I know the first one is a variable and maybe the second is only a string, is that it? Is there any way of making this work?

I know I might be asking something quite obvious for many, but I am just starting. Any help appreciated! :)

  • variables cannot be accessed in javascript in this way. you can store the value in an object (the global window object, or otherwise, and then look up values that way) – mikkelrd Oct 26 '17 at 20:39
  • Thank you for such a fast answer! I will look a each comment/answer closely (try it) and let you know. –  Oct 26 '17 at 20:41

3 Answers3

2

You should probably use an object instead:

var data = {
  var1: 58
};

for(var i = 0; i < 10; i++){
 if(data["var" + i] == 58) {
   console.log("they are equal");
 }
}

UPD: @Alex suggested a variant with window instead of data, which could be treated as global object. It works in browsers, but you should know that "there is no public standard that applies to the window object" (MDN).

dhilt
  • 18,707
  • 8
  • 70
  • 85
  • Or even better, just an array of 10 entries. – Bergi Oct 26 '17 at 20:42
  • @dhilt, your answer indeed worked! thank you very much. Now for the sake of knowledge, maybe you know where I could read something more about it? (I will accept the answer as correct as soon as it allows me to do it). –  Oct 26 '17 at 20:48
  • @MrUnity Not sure if I can recommend any good link on on "how the object works" or "what is the object", it is very basic term in javascript and all you need is just to start learning from the beginning. So continue your research, ask here new questions and good luck! – dhilt Oct 26 '17 at 20:57
  • @dhilt, Hahaha your answer made me laugh.Thanks, I will. –  Oct 26 '17 at 21:01
  • @Bergi, I will take a look to your approach too. Thanks! –  Oct 26 '17 at 21:04
1
var var1 = 58;

for(var i=0 ;i<10;i++){
    if(window["var"+i] === 58) {
         console.log("they are equal");
    }
 }
Alex
  • 4,621
  • 1
  • 20
  • 30
0

dhilt's answer is probably better, but maybe you don't have the ability to change the other variable.

var var1 = 58;

for (var i = 0; i < 10; i++) {
  var cur;
  try {
    cur = eval('var' + i);
  } catch (error) {
    cur = null;
  }
  if (cur === 58) {
    console.log("they are equal");
  }
}
Amos47
  • 695
  • 6
  • 15