How do I work around JavaScript's parseInt octal behavior?

后端 未结 10 1783
Happy的楠姐
Happy的楠姐 2020-11-21 07:36

Try executing the following in JavaScript:

parseInt(\'01\'); //equals 1
parseInt(\'02\'); //equals 2
parseInt(\'03\'); //equals 3
parseInt(\'04\'); //equals          


        
10条回答
  •  后悔当初
    2020-11-21 07:48

    You may also, instead of using parseFloat or parseInt, use the unary operator (+).

    +"01"
    // => 1
    
    +"02"
    // => 2
    
    +"03"
    // => 3
    
    +"04"
    // => 4
    
    +"05"
    // => 5
    
    +"06"
    // => 6
    
    +"07"
    // => 7
    
    +"08"
    // => 8
    
    +"09"
    // => 9
    

    and for good measure

    +"09.09"
    // => 9.09
    

    MDN Link

    The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

提交回复
热议问题