Type conversion of Boolean to Number in JavaScript

前端 未结 3 985
春和景丽
春和景丽 2021-01-27 09:22

I was working on type conversion of Boolean values to Number in javascript.

console.log(new Number(true));//Prints 1
console.log(+true);//Prints 1
console.log(pa         


        
相关标签:
3条回答
  • 2021-01-27 09:41

    If you are actually working on number conversions then this table might be very helpful:

    0 讨论(0)
  • 2021-01-27 09:45

    Number constructor invokes toNumber internally which as per spec

    Boolean - Return 1 if argument is true. Return +0 if argument is false.

    Which means Number(true) returns 1.

    However, parseInt invokes toString internally and as per spec

    Boolean
    If argument is true, return "true".

    If argument is false, return "false".

    Which means parseInt(true) -> parseInt("true") -> NaN

    since as per spec again

    1. If number is NaN, +0, −0, +∞, or −∞, return +0.

    Hope this helped.

    0 讨论(0)
  • 2021-01-27 09:58

    Because parseInt expects a string and 'true' is NaN.

    From MDN:

    parseInt()

    The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

    0 讨论(0)
提交回复
热议问题