Javascript 如何将其更改为for循环?

Javascript 如何将其更改为for循环?,javascript,Javascript,我有一个小脚本,如果我找不到一种方法将它放入for循环,它将变得巨大 if(buildLevel >= 2){ $( "#house1").html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house1.jpg' />" ); } if(buildLevel >= 3){ $( "#

我有一个小脚本,如果我找不到一种方法将它放入for循环,它将变得巨大

if(buildLevel >= 2){
    $( "#house1").html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house1.jpg' />"  );
}
if(buildLevel >= 3){
    $( "#house2").html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house2.jpg' />"  );
}
if(buildLevel >= 4){
    $( "#house3").html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house3.jpg' />"  );
}
如你所见。包括图像名称在内的所有数字每次应增加1。因此,如果会有一个额外的“房子”,它将是这样的:

if(buildLevel >= 5){
    $( "#house4").html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house4.jpg' />"  );
}

我希望任何人都能帮助我。我找不到好的解决方案。

您可以这样做,使用buildLevel作为for循环的结束条件:

for ( var i=1 ; i< 6; i++){
 if(buildLevel >= i){
      $( "#house"+i).html( "<img style='width: 200px; height: 150px; top:0; left:          0; position: absolute;' data-u='image' src='images/house'+i+'.jpg' />"  );
  }
}

将此作为最干净的解决方案。谢天谢地,你可能很匆忙,这无论如何都不是正确的答案。房子应该比柜台少一个,这一点在问题中被清楚地提到了。为我自己修复了那个部分。老实说,其余的都很不错。谢谢你对这个答案进行了修正,@deepeshkumar.See man house应该比counter少一个,这在问题中已经明确提到了。看看我的答案。
for (var i = 1; i < buildLevel; i++) {
    $( "#house" + i).html( "<img style='width: 200px; height: 150px; top:0; left: 0; position: absolute;' data-u='image' src='images/house'+i+'.jpg' />"  );
}