0

I would like to find a more serious code for the one below. I am looping through a number of variables (player1, TSP1, player2, TSP2,...). Here is the ugly code, that works fine:

if (TSP1 < player1) {
    $("#errornotice").html("Minimum TSP player 1 " is " + player1);
    player1-list.focus();
} else if (TSP2 < player2) {
    $("#errornotice").html("Minimum TSP player 2 " is " + player2);
    player2-list.focus();
} else if (TSP3 < player3) {
    $("#errornotice").html("Minimum TSP player 3 " is " + player3);
    player3-list.focus();
} else if (TSP4 < player4) {
    $("#errornotice").html("Minimum TSP player 4 " is " + player4);
    player4-list.focus();
}

<b><span style="color:red" id ="errornotice"></span></b><br> 

How can I get it to do the same less ugly in a loop ? Something like this:

for (var a = 1; a < 4; a++){
     if (TSP+a < speler+a) {
          $("#errornotice").html("Minimum TSP player" +a+ " is " + player+a);
          Thuisspeler1-list+a.focus();
      }
}

Obviously, the syntaxis is completely wrong, but that's just to give you an idea of what I would like to achieve. I am really stuck here, so all help is greatly appreciated.

1
  • for (var a = 1; a < 4; a++){ if (thuisTSP+a < speler+a) { $("#errornotice").html("Minimum TSP player" +a+ " is " + player+a); Thuisspeler1-list+a.focus(); } } Commented Dec 11, 2018 at 15:01

2 Answers 2

1

Not sure to understand the purpose of the code snippet, so sorry if this look obvious to you, but:

  • Have you look at switch / case command?
  • Have those variables to be set like that, can't you get an array instead?
Sign up to request clarification or add additional context in comments.

1 Comment

alak, I have looked at those possibilities, but didn't find a solution that way either. Can you maybe illustrate how that code would look in detail ?
0

I recommend reading this, How to reference a variable dynamically in javascript .

8 Comments

Thx Joss. But I still can't get it to work. Any idea what is still wrong here? I added the new code in the original post.
for (var a = 1; a < 4; a++){ if (TSP[a] < speler[a]) { $("#errornotice").html("Minimum TSP player" +a+ " is " + player[a]); Thuisspeler1-list[a].focus(); } }
Putting the variable between [] is not the whole solution, is it ?
You need to build an object containing the variable names and their corresponding values. You can then loop through this object like so: myObject['string' + int]. Note that it's the second solution] on that page that is most relevant to you: stackoverflow.com/a/3834401/9636451
Maybe I am asking my question the wrong way. Let me try another way. What if I wanted to alert 20 variables one after the other and their names were variable1, variable2,... Would this work in js: Code: for (var a = 1; a < 20; a++){alert(variable[a]);}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.