使用if语句检查是否为NaN

using an if statement to check if NaN

本文关键字:NaN 是否 检查 if 语句 使用      更新时间:2023-09-26

我从表单中获取一个数值。然后检查它是否为NaN。如果它是一个数字,我想将该值设置为一个变量。问题是,当我输入一个有效的数字时,我仍然会收到一个警报,并且该数字不会传递给变量"日期"。我应该如何修改我的语句,以便当它是一个有效的数字时,我可以将其分配给可变日期?

var adate = document.getElementById("dueDate").value;    
    if ( adate == NaN || " ") {
    alert("Please enter a due date");
    return;
    }
    else {
    var date = (new Date()).setDate(adate);
    }
    processDate(date);

使用Javascript的isNaN((函数。

根据IEEE的标准,用NaN检查相等性总是错误的。斯蒂芬·卡农,IEEE-754委员会的成员,决定了这一点,在这里有一个很好的答案来解释这一点。

尽管看起来很奇怪,NaN !== NaN

if (adate !== adate || adate !== " ") {
  //...
}

isNaN函数在很多情况下都能工作。不过,有一个很好的理由可以证明它坏了。

解决这一问题的一个好方法是:

MyNamespace.isNaN = function (x) {
  return x !== x;
}

您可以使用if( isNaN(adate))

祝好运

这里有两个问题。结果是条件总是会通过。这就是它的作用:

adate == NaN // first, test if adate == NaN (this always returns false)
||           // if the first test fails (i.e. always), carry on checking
" "          // test if the string " " is truthy (this always returns true)

||进行两次单独的检查。它不测试adate是否为"NaN" "",这似乎是您所期望的。

你的代码可能会说

if ( true ) {

然而,如果你尝试两种比较,你就可以解决这个问题:

if ( (adate == NaN) || (adate === " ")) {

然而,正如其他人所说,这并不奏效,因为NaN !== NaN。因此,解决方案是使用isNaN:

if (isNaN(adate) || (adate === " ")) {

通过使用isNaN方法,我们可以验证给定的输入是否为数字

let num1 = parseInt(prompt('Enter your number-1'));
let num2 = parseInt(prompt('Enter your number-2'));
alert(num1 + " is of type " + typeof num1 + " & " + num2 + " is of type " + typeof num2);
if (isNaN(num1) || isNaN(num2)) {
  alert("Can not add incompatible types");
} else {
  let sum = num1 + num2;
  alert("Sum is " + sum);
}