0

所以下面是导致我问题的代码片段。在此之前有一堆东西可以正常工作。

if (numWOOD_OK) 
    {
    return true;    
    }
else {  
    alert("Number of bags must be a whole number");
    return false;                             
    }   
if (numDISTANCE<=0)                             
    {                       
    alert("Input for distance is invalid");                 
    return false;                       
    }

基本上,if (numWOOD_OK)它正在运行之前声明的 RegExp,如果它返回 false,则表示已在相关输入框中输入了一个小数 - 这是我们不想要的。

if (numDISTANCE<=0)检查特定输入框是否为空。它的设置方式与if (numWOOD_OK).

问题是,if (numDISTANCE<=0)不会触发。谁能告诉我为什么?

4

3 回答 3

3

You always return true or false before you reach that if condition, so it will never execute.

You can rewrite to make it work like this:

if (!numWOOD_OK)  {
    alert("Number of bags must be a whole number");
    return false;                             
}   
if (numDISTANCE<=0) {                       
    alert("Input for distance is invalid");                 
    return false;                       
}
return true;
于 2013-05-16T00:44:11.950 回答
0

Whatever function your inside ends with one of those return statements above it. If you have code like this

if(this) {
    return true;
} else {
    return false;
}
// this part will never execute
于 2013-05-16T00:44:56.280 回答
0

By the time the code gets to that if, it will have already returned from the function. Returning short-circuits the logic and stops the function immediately. You might consider using a local variable to store the return value, and return that at the end:

var ret;
if (numWOOD_OK) 
    {
    ret = true;
    }
else {  
    alert("Number of bags must be a whole number");
    ret = false;                        
    }   
if (numDISTANCE<=0)                             
    {                       
    alert("Input for distance is invalid");                 
    ret = false;     
    }
return ret;
于 2013-05-16T00:45:56.103 回答