0

JavaScript parseInt() 的工作方式似乎与 Java parseInt() 不同。

一个非常简单的例子是:

document.write(parseInt(" 60 ") + "<br>");  //returns 60
document.write(parseInt("40 years") + "<br>");  //returns 40
document.write(parseInt("He was 40") + "<br>");  //returns NaN

1号线没问题。但我希望第 2 行会出错,因为您实际上无法将“年”转换为整数。我相信 JavaScript parseInt() 只是检查字符串中的前几个字符是否是整数。

那么如何检查只要字符串中有非整数,它就会返回 NaN?

4

5 回答 5

4

parseInt 旨在为解析整数提供一定的灵活性。Number 构造函数对额外字符不太灵活,但也会解析非整数(感谢 Alex):

console.log(Number(" 60 "));  // 60
console.log(Number("40 years"));  // Nan
console.log(Number("He was 40"));  // NaN
console.log(Number("1.24"));  // 1.24

或者,使用正则表达式。

" 60 ".match(/^[0-9 ]+$/);  // [" 60 "]
" 60 or whatever".match(/^[0-9 ]+$/);  // null
"1.24".match(/^[0-9 ]+$/);  // null
于 2013-03-26T02:49:12.890 回答
0

下面是一个isInteger可以添加到所有 String 对象的函数:

// If the isInteger function isn't already defined
if (typeof String.prototype.isInteger == 'undefined') {

    // Returns false if any non-numeric characters (other than leading
    // or trailing whitespace, and a leading plus or minus sign) are found.
    //
    String.prototype.isInteger = function() {
        return !(this.replace(/^\s+|\s+$/g, '').replace(/^[-+]/, '').match(/\D/ ));
    }
}

'60'.isInteger()       // true
'-60'.isInteger()      // true (leading minus sign is okay)
'+60'.isInteger()      // true (leading plus sign is okay)
' 60 '.isInteger()     // true (whitespace at beginning or end is okay)

'a60'.isInteger()      // false (has alphabetic characters)
'60a'.isInteger()      // false (has alphabetic characters)
'6.0'.isInteger()      // false (has a decimal point)
' 60 40 '.isInteger()  // false (whitespace in the middle is not okay)
于 2013-03-26T03:01:50.260 回答
0

要检查字符串是否包含非整数,请使用正则表达式:

function(myString) {
  if (myString.match(/^\d+$/) === null) {  // null if non-digits in string
    return NaN
  } else {
    return parseInt(myString.match(/^\d+$/))
  }
}
于 2013-03-26T02:51:25.263 回答
0

我会使用正则表达式,可能类似于以下内容。

function parseIntStrict(stringValue) { 
    if ( /^[\d\s]+$/.test(stringValue) )  // allows for digits or whitespace
    {
        return parseInt(stringValue);
    }
    else
    {
        return NaN;
    }
}

于 2013-03-26T02:54:22.290 回答
0

最简单的方法可能是使用一元加号运算符:

var n = +str;

不过,这也会解析浮点值。

于 2013-03-26T02:57:39.633 回答