2012-07-07 16 views
0

这似乎并不奏效,我不知道如何得到这个while循环正常工作的任何帮助,将不胜感激。while循环不与正常工作>标记

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() 
+0

什么是 “工作不正常”?发生了什么以及你期望发生什么? – 2012-07-07 13:51:59

+0

以及< 1 || > 9999位如果你检查Web控制台它说>是一个意外的令牌为什么? – thechrishaddad 2012-07-07 13:54:17

回答

5

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

while (productCode < 1 || productCode > 9999) 
          ^^^^^^^^^^^ 

和:

  • 供应基数,以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; 
} 

我还没有实现的treshold,它是由你来做到这一点。

+0

为什么我的循环不断重复,当我输入一个数小于1或大于9999,你怎么打破它,一旦我输入一个有效的数字,因为它只是不断循环现在@ – thechrishaddad 2012-07-07 14:04:53

+0

见user1265535我更新的答案,弹点5 – 2012-07-07 14:05:21

+0

函数getProductCode(){ \t productCode = parseInt(prompt(“Enter Product Code:”)); \t而 \t { \t \t document.writeln( “错误产品编号必须是(1之间 - 9999)!”)((PRODUCTCODE> = 1 || PRODUCTCODE = <9999)!); \t \t parseInt(提示(“输入产品代码:”)); \t} \t回PRODUCTCODE } getProductCode() – thechrishaddad 2012-07-07 14:05:27

2

它应该是:

while (productCode < 1 || productCode > 9999) 
0

(productCode < 1 || > 9999)在语法上不是有效的表达式

你可能想(productCode < 1 || productCode > 9999)