我有一个功能可以测试提示输入是否为数字,如下所示:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
但是每次输入数字时,它都会一直输出hello +数字。我已经使用了一段时间了,但是对我来说这没有意义,似乎应该可以使用。人为什么返回真实?
您的代码是使用isNaN方法的正确方法。但是,对于任何其他阅读此文章的人,我都看到了一个奇怪的异常,其中记录在案的IsNaN用法无法正常工作,我通过将parseInt方法与IsNaN方法结合使用解决了这个问题。根据W3c网站(https://www.w3schools.com/jsref/jsref_isnan.asp),IsNan('123 ')应该返回false,而IsNan('g12')应该返回true,但是我已经看到了一些情况如果不是这种情况。如果您无法使用已记录的方法,请尝试以下代码:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
另外,您可以尝试这种经过良好测试的方法。
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句