簡體   English   中英

帶有 JavaScript while 和 do while 嵌套循環的乘法表

[英]multiplication table with JavaScript while and do while nested loops

我在使用 JavaScript 嵌套循環的乘法表時遇到問題。 For 循環正常工作。 但我有一段時間的問題:

while (i <= 10) {
  while (j <= 10) {
    document.write(i * j + " ")
    j++
  }
  document.write("<br>")
  i++

}

此代碼正在打印:

1 2 3 4 5 6 7 8 9 10

同時做:

step = 1
step1 = 1
do {
  do {
    document.write(step * step1 + " ")
    step1++
  } while (step1 < 10)
  step++
} while (step < 10)

此代碼正在打印:

1 2 3 4 5 6 7 8 9 20 33 48 65 84 105 128 153

這是完整的代碼:

 <.DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> i = 1 j = 1 while (i <= 10) { while (j <= 10) { document.write(i * j + " ") j++ } document.write("<br>") i++ } step = 1 step1 = 1 do { do { document.write(step * step1 + " ") step1++ } while (step1 < 10) step++ } while (step < 10) </script> </body> </html>

在每次啟動該循環之前,您需要將內部循環的變量設置回1

 let i = 1; while (i <= 10) { let j = 1; while (j <= 10) { document.write(i * j + " ") j++ } document.write("<br>") i++ }

否則,當你重復外循環時,內循環的結束條件已經滿足,所以內循環只運行一次。

這就是為什么通常首選for循環的原因——你不能輕易忘記初始化步驟。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM