javascript IsNaN and 0

javascript IsNaN and 0

本文关键字:and IsNaN javascript      更新时间:2023-09-26

我有一些代码返回意想不到的结果。

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,它不应该碰到ifelse if语句。JS是否认为0是NaN,即使typeof表明它是一个数字?

0 == ''true,因此isNaN部分甚至不会被评估。

===代替==

您正在与"just"双等号进行比较,因此0 == ''(在浏览器的控制台中尝试)。

解决这个问题的一种方法是使用三重等号。另一种方法是完全删除parseInt,这样ccVal将保持为字符串。字符串到字符串的比较将按照预期('' != '0')。

删除parseInt还可以解决另一个问题(您没有传递基数,但必须)。它到底为什么会在那里?