The default value of parseInt is 10

One of the bad parts of JavaScript is that if you use parseInt with something starting with 0, then it can see the number as octal.

i = parseInt(014); // Answer: 12

Q: How can I redefine parseInt so that it uses radix 10 by default? I assume that you would use a prototype method.

Edit:

Maybe I should do this:

$.fn.extend({
    parseInt:function(X) {
        return parseInt(X,10);
    }
});
+5
source share
6 answers

If you keep a link to the original function parseInt, you can overwrite it with your own implementation;

(function () {
    var origParseInt = window.parseInt;

    window.parseInt = function (val, radix) {
        if (arguments.length === 1) {
            radix = 10;
        }

        return origParseInt.call(this, val, radix);
    };

}());

. , , , , . , , , ?

;

function myParseInt(val, radix) {
    if (typeof radix === "undefined") {
        radix = 10;
    }

    return parseInt(val, radix);
}
+13

-, parseInt :

  • 0x - .
  • 0 -
  • else decimal

, , 0;)

ECMA-262 ( EcmaScript 5, aka 5) - , "use strict"

, :

  • 0x - hex
  • else decimal

- radix 8.

ECMAScript 5 , , , . , , , , , .

IE 10 Chrome 19 - IE , Chrome .

Chrome 19 versus IE 10 Release Preview

- : http://repl.it/CZO# 10, 10, 8, 10, 16, - : (

+6

, parseInt('014'), parseInt(014).

parseInt ( ), , - :

(function(_parseInt)
{   
    parseInt = function(string, radix)
    {    return _parseInt(string, radix || 10);
    };

})(parseInt);
+5

. - :

function createIntParser(radix) {
    return function(val) {
        return window.parseInt(val, radix);        
    }
}

decimalParseInt = createIntParser(10);

alert(decimalParseInt("010"));โ€‹

.

+4
i = parseInt('014',10);

, 014, 12, parseInt .

JavaScript: (014 === 12);

+2

There is a second parameter for parseInt():

parseInt(x, [radix])

http://www.javascriptkit.com/jsref/globalfunctions.shtml

+1
source

All Articles