简体   繁体   中英

Loop through changing variables

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.

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?

我建议阅读此内容, 如何在javascript中动态引用变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM