Javascript,不显示未定义的数字

时间:2013-02-21 11:32:21

标签: javascript

我创建了一个带有键和值的变量,如下所示:

var e = new Array();
e[0] = "Bitte";
e[1] = "Danke";

除此之外,我在变量中添加了一行,当数字未定义时显示文本。

e[NaN] = "Change Settings"; 

因此,当变量eNaN(“未定义”)时,我希望他不会在输入中显示变量e的数量。我试图实现这一目标,但它不会起作用。

if (neuezahl = NaN) {
  document.getElementById("saveServer").value="";
} else {
  document.getElementById("saveServer").value=""+neuezahl+""; 
}

3 个答案:

答案 0 :(得分:5)

您已指定neuzahl未对其进行比较,除此之外使用isNAN功能:

if (isNAN(neuezahl))
{
   document.getElementById("saveServer").value="";
}
else 
{
   document.getElementById("saveServer").value=""+neuezahl+""; 
}

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/isNaN

答案 1 :(得分:2)

NaN无法直接比较(它甚至不等于自身NaN === NaN ==> false)。使用isNaN()检测NaN

if (isNaN(neuezahl)) {...}

答案 2 :(得分:0)

if语句中的条件可能不正确。现在使用“=”而非“==”,它是赋值语句,条件将始终为true。因此,如果你想检查“neuezahl”是“NaN”,函数isNaN可能有所帮助。

if (isNaN(neuezahl)){...}
else {}