我有一些代码会返回意外的结果.
Select a card
***********8431
Use a new card
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 ==”为真,因此isNaN部分甚至不会被评估.
使用===而不是==.
标签:zero,javascript,nan
来源: https://codeday.me/bug/20190723/1510320.html