【问题标题】:Display numbers in a order using for loop in JavaScript在 JavaScript 中使用 for 循环按顺序显示数字
【发布时间】:2019-12-09 14:14:34
【问题描述】:

我尝试了这段代码并得到了以下输出:

<script type="text/javascript">

document.write("<table border='1' width='70%'>");
    for(var a=1;a<=20;a=a+5){
      document.write('<tr>');
      for(var b=a;b<a+5;b++){

          document.write("<td>"+b+"</td>");

      }
      document.write('</tr>');
    }
    document.write("</table>");

    </script>

输出:

 1  2  3  4  5
 6  7  8  9 10
11 12 13 14 15
16 17 18 19 20

我怎样才能像这样显示输出:

 1  6 11 16
 2  7 12 17
 3  8 13 18
 4  9 14 19
 5 10 15 20

【问题讨论】:

  • 永远不要使用document.write()。永远不要永远使用document.write()来编写部分元素(只是开始或结束标签)。

标签: javascript for-loop nested-loops


【解决方案1】:

也许你必须在你问之前尝试一下,
这是我的解决方案,您可以尝试此代码或制作您自己的代码

<script type="text/javascript">

document.write("<table border='1' width='70%'>");

//  I made a condition where a <= 5. because there are 5 columns needed right there.

for(var a=1;a<=5;a++){
  document.write('<tr>');

  // on this loop I made a condition where b <= 20 and the increment b+=5 because every rows show a number multiple 5 start from "a" value to 20

  for(var b=a;b<=20;b+=5){

      document.write("<td>"+b+"</td>");

  }
  document.write('</tr>');
}
document.write("</table>");

</script>

脚本上的描述。我不擅长解释它,如果我的解释有点混乱,对不起

【讨论】:

  • 在不解释问题所在的情况下为 OP 提供解决方案并不能真正帮助 OP 作为程序员发展。
  • 是的,你是对的,对不起,我的错。让我改一下答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多