簡體   English   中英

JavaScript初學者變量混亂

[英]JavaScript beginner variable confusion

從書中學習JS,練習題是:

修改問題1的代碼,要求用戶顯示時間表。 該代碼應繼續請求並顯示時間表,直到用戶輸入-1。 另外,進行檢查以確保用戶輸入的有效號碼; 如果該號碼無效,請要求用戶重新輸入。

這是建議的解決方案:

 function writeTimesTable(timesTable, timesByStart, timesByEnd) { for (; timesByStart <= timesByEnd; timesByStart++) { document.write(timesTable + " * " + timesByStart + " = " + timesByStart * timesTable + "<br />"); } } var timesTable; while ((timesTable = prompt("Enter the times table", -1)) != -1) { while (isNaN(timesTable) == true) { timesTable = prompt(timesTable + " is not a " + "valid number, please retry", -1); } if (timesTable == -1) { break; } document.write("<br />The " + timesTable + " times table<br />"); writeTimesTable(timesTable, 1, 12); } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Chapter 4: Question 2</title> </head> <body> <script> </script> </body> </html> 

這是我的代碼,它也以相同的結果運行,沒有!= -1

 function writeTimesTable(timesTable, timesByStart, timesByEnd) { for (; timesByStart <= timesByEnd; timesByStart++) { document.write(timesTable + " * " + timesByStart + " = " + timesByStart * timesTable + "<br />"); } } var timesTable; while (timesTable = prompt("Enter the times table", -1)) { while (isNaN(timesTable) == true) { timesTable = prompt(timesTable + " is not a " + "valid number, please retry", -1); } if (timesTable == -1) { break; } document.write("<br />The " + timesTable + " times table<br />"); writeTimesTable(timesTable, 1, 15); } 
 <!DOCTYPE html> <html lang="en"> <head> <title>Chapter 4: Question 2</title> </head> <body> <script> </script> </body> </html> 

由於我的代碼運行得很好,為什么在第一個while語句中需要!= -1參數? 為什么在那兒,它有什么用?

-1的檢查幾乎但不是完全多余。 它捕獲條件“用戶取消提示”和“用戶輸入了空字符串”,其結果為false。 在您的版本中,這終止了循環,但要求是在用戶輸入“ -1”處終止。

如果while循環不返回任何內容,它將返回-1 (或false )。 在原始示例的情況下,我假設僅在示例中使用!= -1條件,因此對於初學者而言更有意義。

假設您只想在用戶輸入-2時終止while循環。 為此,您需要在循環中指定!= -2條件,但是-1仍會終止循環。

您要告訴瀏覽器/編譯器在while循環中繼續執行代碼,直到用戶輸入-1。 當timesTable獲得值“ -1”時-也就是說,當用戶輸入“ -1”時-while循環將停止運行。

// timesTable gets what the user enters in the prompt
// while timesTable is not equal to -1, execute the code in brackets
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
  while (isNaN(timesTable) == true) {
    timesTable = prompt(timesTable + " is not a " +
      "valid number, please retry", -1);

暫無
暫無

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

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