Emm*_*myS 3 javascript nan zero
我有一些代码会返回意外的结果.
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>
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,ccVal是0,但它落入else if语句.我希望只有当它不是一个数字时才会发生.预期的结果是它应该落入最后的else声明中.这是一个JSFiddle的结果:http://jsfiddle.net/n2Uy7/
任何人都可以解释为什么会这样吗?如果是0,它不应该打要么if或else if语句.JS是否认为0为NaN,即使typeof表明它是一个数字?