默认parseInt基数为10 [英] Default parseInt radix to 10

查看:217
本文介绍了默认parseInt基数为10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript的一个不好的部分是,如果你使用以0开头的东西使用parseInt,那么它可以将数字视为八进制。

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

问:如何重新定义parseInt以使其默认为基数为10?我假设你会使用原型方法。

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

编辑:

也许我应该这样做:

$.fn.extend({
    parseInt:function(X) {
        return parseInt(X,10);
    }
});


推荐答案

如果存储对原始<$ c的引用$ c> parseInt 函数,你可以用你自己的实现覆盖它;

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);
}

这篇关于默认parseInt基数为10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆