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

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

是否有可能在JavaScript中做这样的事情来检查NaN?

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

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


当前回答

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

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

其他回答

这个问题

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

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

解决方案

我建议使用一个helper函数,它可以解决大部分问题:

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

helper函数将给出以下结果:

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

我创建了一个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

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

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

在我看来,这项工作比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
//////////////////////////////////////////////////////
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