javascript IsNaN and 0
javascript IsNaN and 0
我有一些代码返回意想不到的结果。
HTML:<select name="cc_dropdown[0]" id="cc-dropdown-0" style="display: none;">
<option value="">Select a card</option>
<option value="0" selected="selected">***********8431</option>
<option value="-1">Use a new card</option>
</select>
JS:
var ccVal = parseInt($("#cc-dropdown-0 option:selected").val());
var errors = [];
if( ccVal == -1 ) {
if( $('#cc_number-'+bIdx).val().length <= 0 || !isValidCreditCardNo($('#cc_number-'+bIdx).val()) ) {
errors.push('Invalid Credit card Number');
}
if( $('#cc_name-'+bIdx).val().length <= 0 ) {
errors.push('Please provide the name on the credit card.');
}
if($('#cc_exp_month-'+bIdx).val() == ""){
errors.push('Please Select an Expiration Date.');
}
if($('#cc_exp_year-'+bIdx).val() == ""){
errors.push('Please Select an Expiration Date.');
}
if( !isValidZipcode($('#cc_zip-'+bIdx).val())){
errors.push('Please enter a valid zipcode.');
}
} else if ( ccVal == 'na' || ccVal == '' || isNaN(ccVal)) {
console.log("ccVal inside else if: " + ccVal);
console.log("ccVal type: " + typeof ccVal);
errors.push('Please select a credit card, or enter a new one.')
}
else {
console.log("else");
errors.push("Arg!");
}
console.dir(errors);
在这种情况下,ccVal
是0,但它落入else if语句。我认为只有当它不是一个数字时才会发生这种情况。预期的结果是它应该落在最终的else
语句中。下面是一个JSFiddle的结果:http://jsfiddle.net/n2Uy7/
谁能解释一下为什么会这样?如果它是0,它不应该碰到if
或else if
语句。JS是否认为0是NaN,即使typeof
表明它是一个数字?
0 == ''
是true
,因此isNaN
部分甚至不会被评估。
用===
代替==
您正在与"just"双等号进行比较,因此0 == ''
(在浏览器的控制台中尝试)。
解决这个问题的一种方法是使用三重等号。另一种方法是完全删除parseInt
,这样ccVal
将保持为字符串。字符串到字符串的比较将按照预期('' != '0'
)。
删除parseInt
还可以解决另一个问题(您没有传递基数,但必须)。它到底为什么会在那里?
相关文章:
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- php布尔值's小写AND大写和数字布尔值'可以接受
- setTimeout and V8
- Jquery post and onclick
- Moment js and IOS
- Rails 3.2 and Paloma gem
- Backbone, TypeScript, and super
- iframe and JavaScript on different pages
- JSON and jQuery Search
- Flash and External Javascript
- javascript IsNaN and 0