What is the difference between parseInt() and Number()?

前端 未结 10 966
無奈伤痛
無奈伤痛 2020-11-22 12:02

How do parseInt() and Number() behave differently when converting strings to numbers?

10条回答
  •  半阙折子戏
    2020-11-22 12:27

    Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

    // parsing:
    parseInt("20px");       // 20
    parseInt("10100", 2);   // 20
    parseInt("2e1");        // 2
    
    // type conversion
    Number("20px");       // NaN
    Number("2e1");        // 20, exponential notation
    

    Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

    The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

    Number("010");         // 10
    Number("0o10")         // 8, explicit octal
    
    parseInt("010");       // 8, implicit octal
    parseInt("010", 10);   // 10, decimal radix used
    

    And it can handle numbers in hexadecimal notation, just like parseInt:

    Number("0xF");   // 15
    parseInt("0xF"); //15
    

    In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

    +"2e1";   // 20
    +"0xF";   // 15
    +"010";   // 10
    

提交回复
热议问题