-4

I am console logging a string using a for loop and appending the for loop index number to each string. However, if the string matches the variable name roastAboutCheapLvl1 that I have defined, I want the variable content to be displayed instead.

What I have tried so far:

var roastAboutCheapLvl1 = "it works";

for (var i = 1; i <= 5; i++) {
  var num = [i].toString();
  var a = "roastAboutCheapLvl" + num;
  console.log(a);
}

What I expected:

it works   
roastAboutCheapLvl2  
roastAboutCheapLvl3  
roastAboutCheapLvl4   
roastAboutCheapLvl5

What am I doing wrong in the above attempt?

cssyphus
  • 37,875
  • 18
  • 96
  • 111
mhd HD
  • 15
  • 5
  • 3
    So, use the variable name instead of a string. – Teemu Jan 08 '19 at 18:04
  • do it like this console.log(roastAboutCheapLvl1); – Wellwisher Jan 08 '19 at 18:06
  • What output are you expecting? – Ihsahs Jan 08 '19 at 18:07
  • maybe you are looking for an object containing your values `{ "Lvl1": "foo", "Lvl2": "bar" }` and then access them with your `a` variable. However I just guessed that, your question is not clear enough for a real answer – Ulysse BN Jan 08 '19 at 18:07
  • i think you should google it first – Amitoj Singh Ahuja Jan 08 '19 at 18:07
  • I am pretty sure you are trying to create variable names dynamically (i.e. concat two strings to create an existing variable name), and then test if that dynamically-created variable name currently exists. If so, see my answer. – cssyphus Jan 08 '19 at 18:25
  • @mhdHD - Have any of the below answers solved your problem? If so, please choose a correct answer so the question will be closed. If not, please edit your question (or post a comment below one of the answers) to tell us what you need. – cssyphus Jan 08 '19 at 18:38
  • @mhdHD Did you choose the wrong answer? Please confirm you are **not** trying to build the variable name "on the fly" (i.e. inside the for loop), because the selected answer does not do that - it requires that you spell-out the var name in full for testing/analysis. Also note that the ternary operator is still an if statement, just using a different (single-line) format - so you will need to use one if statement (or ternary statement) for each variable name you wish to build/test in the for loop. *Also, notice that to get the `Object.keys()` info, the full var name was written, not built* – cssyphus Jan 08 '19 at 19:23

3 Answers3

0

I think you are inquiring about creating dynamic variables in javascript. See this example for how to do it.

var roastAboutCheapLvl1 = "it works (1)";
var roastAboutCheapLvl3 = "it works again (3)";

for (var i = 1; i <= 5; i++) {
  var aa = window['roastAboutCheapLvl' + i];
  if (!aa){
    console.log('roastAboutCheapLvl' + i);
  }else{
    console.log(aa);
  }
  
}

See this answer for explanation:

Use dynamic variable names in JavaScript

cssyphus
  • 37,875
  • 18
  • 96
  • 111
0

Just assign the roastAboutCheapLvl1 variable to an object which will convert the variable to a key: value pair and then retrieve the key from the object.

Add a second if statement inside your for loop that checks if the variable name matches the a and if it does, return the variable else return a.


Check the following Code Snippet for a practical example of what I described:

    var roastAboutCheapLvl1 = "it works";

    let varName = Object.keys({roastAboutCheapLvl1})[0];

    for (var i = 1; i <= 5; i++) {
      var num = [i].toString();
      var a = "roastAboutCheapLvl" + num;
      if (a === varName) {
          console.log(roastAboutCheapLvl1);
      } else {
          console.log(a);
      }
      
    }

Or if you don't want to use an if/else statement, you can use a ternary operator instead like this:

        var roastAboutCheapLvl1 = "it works";

        let varName = Object.keys({roastAboutCheapLvl1})[0];;

        for (var i = 1; i <= 5; i++) {
          var num = [i].toString();
          var a = "roastAboutCheapLvl" + num;
          a === varName ? console.log(roastAboutCheapLvl1) : console.log(a);
        }
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
  • You are hard-coding the variable name that you console.log, so this is not a truly dynamic solution. There is a simpler, more correct way to do this. – cssyphus Jan 08 '19 at 18:27
  • @Gibberish Agreed, Let me try fiddling with the code a bit more. Btw, using `window['roastAboutCheapLvl' + i]` might not be a good idea if there are more than one variable with the same name defined locally in some other function. – AndrewL64 Jan 08 '19 at 18:33
  • is there any chance to do that without using the if statement?? – mhd HD Jan 08 '19 at 18:47
  • @mhdHD Yes, you can use a ternary operator instead. Let me add the approach as an alternative in the answer. – AndrewL64 Jan 08 '19 at 18:50
  • 1
    @mhdHD I have updated the answer to show you how you can replace the five-line `if/else statement` with a one-line `ternary operator`. – AndrewL64 Jan 08 '19 at 18:55
  • how can speak to you in private ?? (i'm new in stack overflow) – mhd HD Jan 08 '19 at 18:59
  • @mhdHD There is no private chat system in StackOverflow at the moment. Can I know why you need to message to me in private? If it is work-related, I can provide you with an email or a link where you can contact me. – AndrewL64 Jan 08 '19 at 19:03
  • Bc, that is not my real problem. That is a clone of my problem although, you make it more difficult to do it – mhd HD Jan 08 '19 at 19:31
  • The ternary operator approach is just two lines extra to your current code. I don't understand how that is difficult. What exactly do you have to do in the original code? – AndrewL64 Jan 08 '19 at 19:34
  • give me ur email ,i can't post my current code on stack overflow – mhd HD Jan 09 '19 at 09:12
-1

I understand what you are trying to do, but you are declaring the variable the wrong way round

When you declare a variable you create what is called a namespace which holds a value.

For example, look at:

var MyFirstVariable = "Hi this is my first variable"

The variable's name is MyFirstVariable

The value of MyFirstVariable is "Hi this is my first variable"

So in order to get your code to work the way you expect you need to write it like this:

    var myVariable = "roastAboutCheapLvl1";
    
    for (let i = 1; i <= 5; i++) {
      var a = "roastAboutCheapLvl" + i.toString();
      if (a === myVariable){
         console.log(a);
      }
    }

Personally i would write it like this:

const myVariable = "roastAboutCheapLvl1";

(you can use const because the variable is constant you are using it to compare something to, it will not be changed or reassigned)

Happy Machine
  • 987
  • 8
  • 30
  • I could be wrong, but I don't think you are addressing the nature of the OP question. Per my reading, the OP is asking how to construct different variable names in a for loop, see if each variable exists, and if so, print its contents. You are checking if the contents of a specified variable are the same as a string that is constructed in the for loop. There is some similarity, but not quite what the question is asking, if I understand correctly. – cssyphus Jan 08 '19 at 19:30
  • @mhdHD - OP, please confirm our understanding of your question . . . ? *If HappyMachine is correct, then I have misunderstood the question and should remove my own answer...* – cssyphus Jan 08 '19 at 19:30