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

后端 未结 10 1630
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:59

    Would it be very naughty to replace parseInt with a version that assumes decimal if it has no second parameter? (note - not tested)

    parseIntImpl = parseInt
    parseInt = function(str, base){return parseIntImpl(str, base ? base : 10)}
    
    0 讨论(0)
  • 2020-11-21 08:04

    Specify the base:

    var number = parseInt(s, 10);
    
    0 讨论(0)
  • 2020-11-21 08:06

    If you know your value will be in the signed 32 bit integer range, then ~~x will do the correct thing in all scenarios.

    ~~"08" === 8
    ~~"foobar" === 0
    ~~(1.99) === 1
    ~~(-1.99)  === -1
    

    If you look up binary not (~), the spec requires a "ToInt32" conversion for the argument which does the obvious conversion to an Int32 and is specified to coerce NaN values to zero.

    Yes, this is incredibly hackish but is so convenient...

    0 讨论(0)
  • 2020-11-21 08:07

    If you've done a bunch of coding already with parseInt and don't want to add ",10" to everything, you can just override the function to make base 10 the default:

    window._oldParseInt = window.parseInt;
    window.parseInt = function(str, rad) {
        if (! rad) {
            return _oldParseInt(str, 10);
        }
        return _oldParseInt(str, rad);
    };
    

    That may confuse a later reader, so making a parseInt10() function might be more self-explanatory. Personally I prefer using a simple function than having to add ",10" all the time - just creates more opportunity for mistakes.

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