最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

nan - javascript IsNaN and 0 - Stack Overflow

programmeradmin3浏览0评论

I have some code that's returning unexpected results.

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);

In this case, ccVal is 0, and yet it's falling into the else if statement. I would expect that to happen only if it's not a number at all. Expected result is that it should fall into the final else statement. Here's a JSFiddle with the results: /

Can anyone explain why this would be the case? If it's 0, it should not hit either the if or the else if statements. Does JS consider 0 to be NaN, even though typeof indicates that it is a number?

I have some code that's returning unexpected results.

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);

In this case, ccVal is 0, and yet it's falling into the else if statement. I would expect that to happen only if it's not a number at all. Expected result is that it should fall into the final else statement. Here's a JSFiddle with the results: http://jsfiddle/n2Uy7/

Can anyone explain why this would be the case? If it's 0, it should not hit either the if or the else if statements. Does JS consider 0 to be NaN, even though typeof indicates that it is a number?

Share Improve this question asked Mar 4, 2013 at 21:38 EmmySEmmyS 12.1k49 gold badges103 silver badges160 bronze badges 3
  • 3 First off, you should NEVER use parseInt() without passing the radix parameter. – jfriend00 Commented Mar 4, 2013 at 21:40
  • @jfriend00 - I wasn't aware of that; I don't recall that being an issue the last time I used the function (somewhere around 1997...) So for standard numbering, do I use 10 for base 10? – EmmyS Commented Mar 4, 2013 at 21:47
  • Yes, use 10. The reason is that without that second parameter for the radix if there is a leading zero or leading 0x in the string to be parsed parseInt() may treat it as octal or hexadecimal. I say "may" because it depends on the browser and whether you're in strict mode. (And of course for user-entered data the user may enter a leading 0, however unlikely that may seem - not a problem for your hardcoded select values, but still it's good to get in the habit of always supplying the radix.) – nnnnnn Commented Mar 4, 2013 at 21:48
Add a ment  | 

2 Answers 2

Reset to default 7

0 == '' is true so the isNaN part doesn't even get evaluated.

Use === instead of ==.

You are paring with "just" double equals signs, so 0 == '' (try it in your browser's console).

One way to fix the issue is to use triple equals instead. Another way is to remove the parseInt entirely, so ccVal will remain a string. String to string parisons will then behave as expected ('' != '0').

Removing the parseInt would also solve another issue (you are not passing in the radix, but you must). Why is it there anyway?

发布评论

评论列表(0)

  1. 暂无评论