2016-08-19 98 views
-1

是否可以写类似:如果有什么的Equals为NaN

if(* === NaN){ 
      this = 0; 
     }; 

我试图做的是赶上计算为NaN的所有数学或变量,并使其等于0,我可以写如果每次数学计算的语句都一样,但它会很混乱,我希望有这样一个简单的解决方案。

+1

没什么等于'NaN'。即使'NaN === NaN; //假' –

+0

那么,你需要使用['isNaN'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN),你不能分配到'this'。 'this = anything'是无效的。 –

+0

您需要查看所有变量,没有“所有” – epascarello

回答

0

你可以做这样的事情

function convertIfNaN (x) { 
    if (isNaN(x)) 
     return 0; 
    else 
     return x; 
} 
0

可以使用isNaN功能,像这样:

if (isNaN(x)) { 
    // do something 
} 

内置的isNaN功能只检查是否值可强制转换为一个数。您也可以编写自己的函数来简单地检查值“南”,例如:

function isNaN(x){ 
    return x !== x; 
} 
+0

我认为这与我期望达到的最接近。看起来简单的巧妙的代码选项并不适合这种情况,我只是做了一个小的if语句的复制粘贴,以便每次在使用变量之前检查它。谢谢! –

-1

我会继续前进,张贴在这里计数器对策:不要使用全球isNaN()功能的JavaScript。它的命名非常糟糕,因为它的工作方式与其签名不符。如果用作数学表达式的一部分,它实际上会检查您在中传递的参数是否将转换为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

等等等等。这种行为并不是不可预测的,但它绝对不是你猜到的,也就是说你会注意到isNaN在告诉你传递的参数是否为实际上是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))

相关问题