Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - Default parseInt radix to 10

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

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

Q: How can I redefine parseInt so that it defaults to radix 10? I'm assuming you would use the prototype method.

Edit:

Maybe I should do this:

$.fn.extend({
    parseInt:function(X) {
        return parseInt(X,10);
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you store a reference to the original parseInt function, 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);
    };

}());

However, I strongly recommend you don't do this. It is bad practise to modify objects you don't own, let alone change the signature of objects you don't own. What happens if other code you have relies on octal being the default?

It will be much better to define your own function as a shortcut;

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

    return parseInt(val, radix);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...