如何将空字符串的 NaN 从 parseInt 转换为 0?

发布于 2024-11-25 06:56:39 字数 281 浏览 3 评论 0原文

在 JavaScript 中解析值时是否可以以某种方式返回 0 而不是 NaN?

如果是空字符串,parseInt 返回 NaN

是否可以在 JavaScript 中执行类似的操作来检查 NaN

var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)

或者也许还有另一个函数或 jQuery 插件可以做类似的事情?

Is it possible somehow to return 0 instead of NaN when parsing values in JavaScript?

In case of the empty string parseInt returns NaN.

Is it possible to do something like that in JavaScript to check for NaN?

var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)

Or maybe there is another function or jQuery plugin which may do something similar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

冧九 2024-12-02 06:56:39
var s = '';
var num = parseInt(s) || 0;

当不与布尔值一起使用时,逻辑 OR || 运算符返回第一个表达式 parseInt(s)(如果它可以计算为 true),否则返回第二个表达式0parseInt('') 的返回值为 NaNNaN 计算结果为 false,因此 num 最终被设置为 0

var s = '';
var num = parseInt(s) || 0;

When not used with boolean values, the logical OR || operator returns the first expression parseInt(s) if it can be evaluated to true, otherwise it returns the second expression 0. The return value of parseInt('') is NaN. NaN evaluates to false, so num ends up being set to 0.

北渚 2024-12-02 06:56:39

您还可以使用 isNaN() 函数:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)

You can also use the isNaN() function:

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
∞觅青森が 2024-12-02 06:56:39

问题

其他答案没有考虑到0是假的,因此以下将是20而不是0:

const myNumber = parseInt('0') || 20; // 20

解决方案

我提出一个辅助函数,可以解决大多数问题:

function getNumber({ value, defaultValue }) {
  const num = parseInt(value, 10);
  return isNaN(num) ? defaultValue : num;
}

辅助函数将给出以下结果:

getNumber({ value: "0", defaultValue: 20 }); // 0
getNumber({ value: "2", defaultValue: 20 }); // 2
getNumber({ value: "2.2", defaultValue: 20 }); // 2
getNumber({ value: "any string", defaultValue: 20 }); // 20
getNumber({ value: undefined, defaultValue: 20 }); // 20
getNumber({ value: null, defaultValue: 20 }); // 20
getNumber({ value: NaN, defaultValue: 20 }); // 20
getNumber({ value: false, defaultValue: 20 }); // 20
getNumber({ value: true, defaultValue: 20 }); // 20

The problem

Other answers don't take into account that 0 is falsy, and thus the following will be 20 instead of 0:

const myNumber = parseInt('0') || 20; // 20

The solution

I propose a helper function, that solves most of the issues:

function getNumber({ value, defaultValue }) {
  const num = parseInt(value, 10);
  return isNaN(num) ? defaultValue : num;
}

The helper function will give the following results:

getNumber({ value: "0", defaultValue: 20 }); // 0
getNumber({ value: "2", defaultValue: 20 }); // 2
getNumber({ value: "2.2", defaultValue: 20 }); // 2
getNumber({ value: "any string", defaultValue: 20 }); // 20
getNumber({ value: undefined, defaultValue: 20 }); // 20
getNumber({ value: null, defaultValue: 20 }); // 20
getNumber({ value: NaN, defaultValue: 20 }); // 20
getNumber({ value: false, defaultValue: 20 }); // 20
getNumber({ value: true, defaultValue: 20 }); // 20
情魔剑神 2024-12-02 06:56:39

我很惊讶没有人提到使用 Number()。当然,如果提供的话,它会解析小数,因此其行为与 parseInt() 不同,但它已经假定基数为 10,并且会将 "" 甚至 " " 转换为 0。

I was surprised to not see anyone mention using Number(). Granted it will parse decimals if provided, so will act differently than parseInt(), however it already assumes base 10 and will turn "" or even " " in to 0.

违心° 2024-12-02 06:56:39

对于不限于 parseInt 的人,您可以使用按位 OR 运算符(隐式调用 ToInt32 到其操作数)。

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

注意:ToInt32parseInt 不同。 (即parseInt('33Ab') === 33

For people who are not restricted to parseInt, you can use the bitwise OR operator (which implicitly calls ToInt32 to its operands).

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Note: ToInt32 is different from parseInt. (i.e. parseInt('33Ab') === 33)

暗藏城府 2024-12-02 06:56:39

在我看来,这项工作比 parseInt 干净得多,使用 + 运算符

var s = '';
console.log(+s);

var s = '1024'
+s
1024

s = 0
+s
0

s = -1
+s
-1

s = 2.456
+s
2.456

s = ''
+s
0

s = 'wtf'
+s
NaN

Does the job a lot cleaner than parseInt in my opinion, Use the +operator

var s = '';
console.log(+s);

var s = '1024'
+s
1024

s = 0
+s
0

s = -1
+s
-1

s = 2.456
+s
2.456

s = ''
+s
0

s = 'wtf'
+s
NaN
最偏执的依靠 2024-12-02 06:56:39

为什么不重写这个函数呢?在这种情况下,您始终可以确保在 NaN 的情况下它返回 0

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

现在,在代码中的任何位置:

parseInt('') === 0

Why not override the function? In that case you can always be sure it returns 0 in case of NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Now, anywhere in your code:

parseInt('') === 0
顾忌 2024-12-02 06:56:39

对于其他寻找此解决方案的人,只需使用: ~~ 而不使用 parseInt,这是最干净的模式。

var a = 'hello';
var b = ~~a;

如果为 NaN,则返回 0。

OBS。该解决方案仅适用于整数

For other people looking for this solution, just use: ~~ without parseInt, it is the cleanest mode.

var a = 'hello';
var b = ~~a;

If NaN, it will return 0 instead.

OBS. This solution apply only for integers

债姬 2024-12-02 06:56:39
var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);
var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);
沩ん囻菔务 2024-12-02 06:56:39
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5
瑾兮 2024-12-02 06:56:39

您可以拥有非常干净的代码,我遇到了类似的问题,我通过使用解决了它:

var a="bcd";
~~parseInt(a);

You can have very clean code, i had similar problems and i solved it by using :

var a="bcd";
~~parseInt(a);
歌入人心 2024-12-02 06:56:39

对空字符串进行单独检查(因为它是一种特定情况),并在这种情况下将其设置为零。

您可以在开头附加“0”,但随后您需要添加前缀以表明它是十进制而不是八进制数

Do a separate check for an empty string ( as it is one specific case ) and set it to zero in this case.

You could appeand "0" to the start, but then you need to add a prefix to indicate that it is a decimal and not an octal number

不交电费瞎发啥光 2024-12-02 06:56:39

我有一个类似的问题(firefox v34),简单的字符串如下:

var myInt = parseInt("b4");

所以我想出了一个快速破解:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

然后让所有愚蠢的复杂处理浮点数+整数用于非简单的东西:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

它将返回 0 对于类似的事情:

var intVal = slowParseNumber("b"); // yeilds 0

I had a similar problem (firefox v34) with simple strings like:

var myInt = parseInt("b4");

So I came up with a quick hack of:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

And then got all stupid complicated to deal with floats + ints for non-simple stuff:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

It will return 0 for things like:

var intVal = slowParseNumber("b"); // yeilds 0
北城半夏 2024-12-02 06:56:39

我创建了一个 2 原型来为我处理这个问题,一个用于数字,一个用于字符串。

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

如果您不想使用安全检查,请使用

String.prototype.tryParseInt = function(){
    /*Method body here*/
};
Number.prototype.tryParseInt = function(){
     /*Method body here*/
};

示例用法:

var test = 1;
console.log(test.tryParseInt()); // returns 1

var test2 = '1';
console.log(test2.tryParseInt()); // returns 1

var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default

var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value

I created a 2 prototype to handle this for me, one for a number, and one for a String.

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

If you dont want to use the safety check, use

String.prototype.tryParseInt = function(){
    /*Method body here*/
};
Number.prototype.tryParseInt = function(){
     /*Method body here*/
};

Example usage:

var test = 1;
console.log(test.tryParseInt()); // returns 1

var test2 = '1';
console.log(test2.tryParseInt()); // returns 1

var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default

var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value
℡Ms空城旧梦 2024-12-02 06:56:39

同样这样,为什么不编写一个函数并在需要时调用它呢?我假设它是进入表单字段以执行计算的内容。

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

这样做有什么问题吗?

Also this way, why not write a function and call it where ever required . I'm assuming it's the entry into the form fields to perform calculations.

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

what's wrong doing this?

人海汹涌 2024-12-02 06:56:39

这是我正在使用的 tryParseInt 方法,它将默认值作为第二个参数,因此它可以是您需要的任何内容。

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558

Here is a tryParseInt method that I am using, this takes the default value as second parameter so it can be anything you require.

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558
○闲身 2024-12-02 06:56:39

仍然允许使用基数的辅助函数

function parseIntWithFallback(s, fallback, radix) {
    var parsed = parseInt(s, radix);
    return isNaN(parsed) ? fallback : parsed;
}

an helper function which still allow to use the radix

function parseIntWithFallback(s, fallback, radix) {
    var parsed = parseInt(s, radix);
    return isNaN(parsed) ? fallback : parsed;
}
心舞飞扬 2024-12-02 06:56:39
// implicit cast
var value = parseInt(tbb*1); // see original question

对于那些不觉得它微不足道的人来说,解释一下:

乘以一,一种称为“隐式转换”的方法,尝试将未知类型操作数转换为原始类型“数字”。特别是,一个空字符串将变成数字 0,使其成为 parseInt() 的合格类型...

PirateApp 上面也给出了一个很好的例子,他建议在前面添加 + 号,强制 JavaScript 使用 Number 隐式强制转换。

8 月 20 日更新:parseInt("0"+expr); 提供更好的结果,特别是 parseInt("0"+'str');

// implicit cast
var value = parseInt(tbb*1); // see original question

Explanation, for those who don't find it trivial:

Multiplying by one, a method called "implicit cast", attempts to turn the unknown type operand into the primitive type 'number'. In particular, an empty string would become number 0, making it an eligible type for parseInt()...

A very good example was also given above by PirateApp, who suggested to prepend the + sign, forcing JavaScript to use the Number implicit cast.

Aug. 20 update: parseInt("0"+expr); gives better results, in particular for parseInt("0"+'str');

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文