遍历变化的变量

时间:2018-12-11 14:26:49

标签: javascript for-loop variables

我想为下面的代码找到更严肃的代码。我正在遍历多个变量(player1,TSP1,player2,TSP2等)。 这是丑陋的代码,可以正常工作:

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> 

我如何才能使其在循环中减少丑陋程度? 像这样:

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();
      }
}

显然,语法是完全错误的,但这只是为了让您了解我想要实现的目标。我真的被困在这里,因此非常感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

不确定是否要理解代码段的目的,如果您觉得这很明显,请抱歉,但是

  • 您看过switch / case命令吗?
  • 具有那样设置的变量,您不能获取数组吗?

答案 1 :(得分:0)

相关问题