是否可以编写如下内容:
if( * === NaN){
this = 0;
};
我要做的是捕获计算为NaN的任何数学或变量并使它们等于0.我可以为每次数学运算写出相同的if语句但是它会很混乱我希望那里这是一个简单的解决方案。
答案 0 :(得分:0)
我不这么认为,因为据我所知,没有什么比NaN更重要了。但是,您可以利用它并执行:
if( * !== *){
//code when * is NaN
};
只有NaN符合条件。 I read this is safer than just to use isNaN()。
答案 1 :(得分:0)
你可以做这样的事情
function convertIfNaN (x) {
if (isNaN(x))
return 0;
else
return x;
}
答案 2 :(得分:0)
您可以像这样使用isNaN函数:
<!--[if gte mso 12]>
<td>
<img src="fallback.jpg">
</td>
<![endif]-->
<!--[if !gte mso 12]><!-- -->
<td>
<img src="animated.gif">
</td>
<!--<![endif]-->
内置的isNaN函数仅检查值是否可以强制转换为数字。您也可以编写自己的函数来简单地检查值“NaN”,如下所示:
if (isNaN(x)) {
// do something
}
答案 3 :(得分:-1)
我必须继续并在此处发布反对响应:不要在JavaScript中使用全局isNaN()
函数。它名称非常糟糕,因为它的工作方式与其签名不符。它实际上会检查您在中传递的参数是否会转换为NaN
,如果用作数学表达式的一部分。或者更简单地说:如果你试图将参数转换为数字,可以转换它。以下是一些例子来说明这一点:
console.log("A number: ", isNaN(42))// it is not "not a number"
console.log("A mathematical concept: ", isNaN(Infinity)) // not a "not a number" still
console.log("NaN: ", isNaN(NaN))// naturally, NaN is not a number
console.log("A garbage operation: ", isNaN(42 * "watermelon"))// its meaningless mathematically, so it produces NaN as a result
console.log("A letter: ", isNaN("a"))// clearly not an NaN value, but if converted to a number, it would be
console.log("An object: ", isNaN({}))// same as above
//entering some more bizarre territory
console.log("An empty string: ", isNaN("")) //really? Yes - it will be converted to a zero, hence it is actually a number
console.log("An empty array: ", isNaN([])) //an empty array converts to an empty string first, then to a zero
console.log("An array with values: ", isNaN(["a", "b", "c"])) //nope, can't convert to a number
console.log("Another array with values: ", isNaN([1, 2, 3])) //neither can this
console.log("An array with a single value: ", isNaN([1])) //of course this can...because it's a SINGLE numeric value in the array
&#13;
依此类推。这种行为不是不可预测的,但它肯定不是你猜的那样,即你会注意到通知isNaN
在告诉你传入的参数是否实际上是非常糟糕的工作< / em> NaN
。
相反,请使用能够提供正确结果的Number.isNaN()
function
console.log("A number: ", Number.isNaN(42))
console.log("A mathematical concept: ", Number.isNaN(Infinity))
console.log("A letter: ", Number.isNaN("a"))
console.log("An object: ", Number.isNaN({}))
console.log("An empty string: ", Number.isNaN(""))
console.log("An empty array: ", Number.isNaN([]))
console.log("An array with values: ", Number.isNaN([1, 2, 3]))
console.log("NaN: ", Number.isNaN(NaN))
&#13;