while循环与>令牌无法正常工作

the*_*dad 0 javascript

这似乎不起作用我不知道如何获得这个循环工作正常任何帮助将不胜感激.

function getProductCode() {
   productCode = parseInt(prompt("Enter Product Code: "));
   while (productCode < 1 || > 9999) 
   {
      document.writeln("Error! the product Code must be between 1 - 9999");
      parseInt(prompt("Enter Product Code: "));
   }
   return productCode
}

getProductCode()
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 5

你错过productCode了左侧的操作数():

while (productCode < 1 || productCode > 9999) 
                          ^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

和:

  • 提供基数parseInt.未指定时,010变为8(八进制文字).
  • 不要将变量泄漏到全局范围,用于var声明局部变量.
  • 反转你的逻辑,或使用isNaN.当提供无效数字(NaN)时,您的循环不应该停止.
  • 最好将消息从document.writeln对话框移动到对话框中.
  • 将新值分配给productCode.否则,你不会走远......
  • 重要提示:可以在浏览器中禁用对话框.不要无限循环多次,但要添加一个阈值.

处理前5个要点的最终代码:

function getProductCode() {
   var productCode = parseInt(prompt("Enter Product Code: "), 10);
   while (!(productCode >= 1 && productCode <= 9999)) {
      productCode = parseInt(prompt("Error! the product Code must be between 1 - 9999\nEnter Product Code: "), 10);
   }
   return productCode;
}
Run Code Online (Sandbox Code Playgroud)

我没有实现阈值,你可以这样做.