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
第一行可以。但我希望第2行给出一个错误,因为你不能实际将"年"转换为整数。我相信JavaScript的parseInt()只是检查字符串的前几个字符是否为整数。
那么我如何检查只要字符串中有非整数,它就会返回NaN?
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
检查字符串是否包含非整数,使用regex:
function(myString) {
if (myString.match(/^d+$/) === null) { // null if non-digits in string
return NaN
} else {
return parseInt(myString.match(/^d+$/))
}
}
我会使用正则表达式,可能像下面这样。
function parseIntStrict(stringValue) {
if ( /^[ds]+$/.test(stringValue) ) // allows for digits or whitespace
{
return parseInt(stringValue);
}
else
{
return NaN;
}
}
最简单的方法可能是使用一元加号运算符:
var n = +str;
这也会解析浮点值
下面是一个可以添加到所有String对象的isInteger
函数:
// 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)