2012-10-09 43 views
2

我正在使用.inArray()來檢查我的數組是否爲'0'值,然後是return false;或者在存在零時中斷函數。在數組中查找值.inArray()

這裏是我目前使用的代碼:

$(document).ready(function() { 

    $('#calc').click(function(e) { 

     var drop = $(".drop"), 
      c = [], 
      g = []; 

     //Push values into an array. 
     drop.each(function() { 
      var $t = $(this), 
       cals = $t.val(), 
       option = $(':selected', this), 
       gly = parseFloat(option.attr('rel')); 
      g.push(gly * 2); 
      c.push(cals * 2); 
     }); 

     var inthere = jQuery.inArray('0', c) > -1; 

     //don't calculate if array is empty 
     if (c.length === 0) { 
      return false; 
     } 
     //don't calculate with a '0' value in array 
     if (inthere == true) { 
      return false; 
     } 

     //shouldn't display if you haven't added a dropdown OR if the dropdown stayed on the "Default" option 
     alert('Passed'); 
    }); 

    $('#add').click(function() { 
     $('#contain').append('<select class="drop"><option value="" rel="" data-default="true">Default</option><option value="1" rel="2">Option 1</option><option value="3" rel="4">Option 2</option></select>'); 
    }); 

});​ 

當用戶離開option在「默認」選項,傳遞給c應該爲0。出於某種原因,價值,代碼將通過,除非我沒有在下拉列表中添加...

如何防止代碼在c數組中存在'0'時繼續?

這裏的fiddle

回答

2

數組沒有一個字符串匹配'0',它有一些配套0

http://jsfiddle.net/DUs8e/1/

var inthere = jQuery.inArray(0, c) > -1; 
+0

我想通了這輸出3秒鐘,然後張貼之前!哈哈,我會問爲什麼,但你也回答了,謝謝! – tcd