繁体   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