2012-01-09 143 views
0

我有以下功能,它会一直返回True。任何想法为什么以及如何避免它?谢谢你们。为什么下面的javascript函数总是返回true?

function validateStatuses(xyx){ 
var umm = ugh[xyx]; 
var selects = $('#cont_'+ugh.xyz+' .status_select'); 
var codes = $('#cont_'+ugh.xyz+' .status_code'); 
for (var i = 0; i < selects.length; i++) { 
    var value = selects[i].options[selects[i].selectedIndex].value; 
    if (value == 'new'){ 
     for (var j = 0; j < codes.length; j++) { 
      var blagh = codes[j].options[codes[j].selectedIndex].value; 
      if(blagh == 13){ 
       $('#info_dialog').html(''); 
       $('#info_dialog').append("<p>You are trying to process a bill ("+bill.name+") with a STATUS of NEW and a STATUS CODE of NONE. Please correct this issue before you proceed!</p><hr />"); 
       $('#info_dialog').dialog({ 
        buttons:{ 
         Cancel: function(){ 
          $(this).dialog('close'); 
         } 
        } 
        }); 
       billCounterAdd(); 
       return false; 
      }//end if   
     }//end for 
    }else{ 
     return true; //this is the problem; 
    }//end if 
}//end for 
}//end Function 
+1

它返回'true',因为在某些时候'if(value =='new')'将条件评估为'false',因此驱动代码流向'else'分支。 – 2012-01-09 15:14:14

+1

任何时候你必须评论块的结尾''}“'通常意味着块太长。 – 2012-01-09 15:14:23

+0

偏离主题,但是由于您似乎正在使用jQuery,因此您可以查看它的['val'](http://api.jquery.com/val/)和['each'](http:// api .jquery.com/val /)函数,这可能有助于简化代码。 – 2012-01-09 15:17:50

回答

3

我敢说你至少有一个选择的值不是'new'。由于您在else子句中执行了return true;,因此第一次选择的值不是'new'将导致该函数返回true。

看起来它确实有错误的返回路径(如果在开始时有'new'选择,并且代码选择的值为13),但也许测试用例没有出现在您的测试中。

为了弄清楚这样的事情有什么问题,没有什么比浏览代码并且看着它在一个体面的调试器中逐行运行。所有主流浏览器现在(最终)都内置了它们,所以你可以看到到底发生了什么,并检查变量等。

+0

+1;敢于离开,好先生。 – 2012-01-09 15:14:46

+0

对好的先生和一个强大的罚款感谢大家的迅速反应。在阅读你的描述之后,我感到很红。我移动了最后一个For循环之外的return true语句以获得所需的效果。 – ringocub 2012-01-09 15:21:34

+0

好的交易,很高兴帮助。 – 2012-01-09 15:28:46

相关问题