How does “+var === +var” work internally to verify if var is numeric?

前端 未结 2 1683
暖寄归人
暖寄归人 2021-02-11 12:30

Seeing this question: Is there a (built-in) way in JavaScript to check if a string is a valid number? and this: jsperf, one of the presented approaches is this (mutatis mutandis

相关标签:
2条回答
  • 2021-02-11 13:16

    + converts the value to a number.

    a gets converted to 123 and 123 === 123.

    b gets converted to NaN but NaN !== NaN (because NaN is never equal to another NaN according step 4a of the equality rules).

    0 讨论(0)
  • 2021-02-11 13:16

    The + operator here is known as the Unary Plus.

    The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already.

    +"123" evaulates as 123.

    +a === +a
    -> +"123" === +"123"
      -> 123 === 123
        -> true
    

    +"123b" evaluates as NaN (Not a Number), as the b character cannot be converted with the Unary Plus as without any prefix (like 0x for hexadecimal) the Unary Plus will assume the value is decimal (0-9). NaN is a special case in that it does not compare against anything, including itself:

    NaN === NaN
    -> false
    
    NaN !== NaN
    -> true
    

    Because of this, our +b test case fails:

    +b === +b
    -> +"123b" === +"123b"
      -> NaN === NaN
        -> false
    

    If you want both to evaluate to true we can add an isNaN() call at the end:

    if ( +a === +a || isNaN(+a) )
    
    if ( +b === +b || isNaN(+b) )
    
    0 讨论(0)
提交回复
热议问题