使用if语句检查是否存在NaN

时间:2013-02-26 18:49:27

标签: javascript if-statement

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

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);

4 个答案:

答案 0 :(得分:14)

使用Javascript的isNaN()功能。

根据IEEE标准,检查与NaN的相等性总是错误的。 决定这一点的IEEE-754委员会成员Stephen Canon有an excellent answer explaining this here

答案 1 :(得分:8)

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

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

isNaN函数可以在很多情况下使用。 There is a good case to be made that it is broken, though

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

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

答案 2 :(得分:4)

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

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 === " ")) {

答案 3 :(得分:2)

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

祝你好运

相关问题