Javascript 对于空字符串,如何将 NaN 从 parseInt 转换为 0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6736476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to turn NaN from parseInt into 0 for an empty string?
提问by Joper
Is it possible somehow to return 0 instead of NaN
when parsing values in JavaScript?
是否有可能以某种方式返回 0 而不是NaN
在 JavaScript 中解析值时?
In case of the empty string parseInt
returns NaN
.
在空字符串的情况下parseInt
返回NaN
。
Is it possible to do something like that in JavaScript to check for NaN
?
是否可以在 JavaScript 中做类似的事情来检查NaN
?
var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)
Or maybe there is another function or jQuery plugin which may do something similar?
或者也许有另一个功能或 jQuery 插件可以做类似的事情?
回答by Matthew
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.
当不与布尔值一起使用时,逻辑 OR ( ||
) 运算符返回第一个表达式 ( parseInt(s)
) 如果它可以被评估为真,否则返回第二个表达式 (0)。的返回值为parseInt('')
NaN。NaN 的计算结果为 false,因此num
最终设置为 0。
回答by gprasant
You can also use the isNaN()
function:
您还可以使用该isNaN()
功能:
var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
回答by Chris Werner
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.
我很惊讶没有看到有人提到使用Number()
. 如果提供的话,它会解析小数,因此其行为与 不同parseInt()
,但它已经假定基数为 10,并且会将 "" 甚至 " " 变为 0。
回答by Ahmad Ibrahim
For people who are not restricted to parseInt
, you can use the bitwise OR operator (which implicitly calls ToInt32
to its operands).
对于不受 限制的人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
Note: ToInt32
is different from parseInt
. (i.e. parseInt('33Ab') === 33
)
注意:ToInt32
不同于parseInt
. (即parseInt('33Ab') === 33
)
回答by sqren
The problem
问题
Other answers don't take into account that 0
is falsy, and thus the following will be 20 instead of 0:
其他答案没有考虑到这0
是假的,因此以下将是 20 而不是 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
回答by PirateApp
Does the job a lot cleaner than parseInt in my opinion, Use the +operator
在我看来,这项工作是否比 parseInt 更干净,使用 +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
回答by Milap Jethwa
var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);
回答by AbdulRahman AlShamiri
//////////////////////////////////////////////////////
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
回答by Fabien Haddadi
// 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()...
乘以 1,一种称为“隐式转换”的方法,试图将未知类型的操作数转换为原始类型“数字”。特别是,空字符串将变为数字 0,使其成为 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.
PirateApp 上面也给出了一个很好的例子,他建议在前面加上 + 号,强制 JavaScript 使用 Number 隐式转换。
回答by bob
I had a similar problem (firefox v34) with simple strings like:
我有一个类似的问题(firefox v34),带有简单的字符串,例如:
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:
对于以下情况,它将返回 0:
var intVal = slowParseNumber("b"); // yeilds 0