How to turn NaN from parseInt into 0 for an empty string?

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?


var s = '';

var num = parseInt(s) || 0;

你也可以使用isNaN()函数:

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

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.

链接地址: http://www.djcxy.com/p/32038.html

上一篇: Tensorflow NaN错误?

下一篇: 如何将NaN从parseInt变为0以获得空字符串?