在Javascript中,什么时候以及为什么数字乘以NaN,然后求值? [英] When and why number evaluates to NaN, after multiplying, in Javascript?
问题描述
根据我的经验,我知道进行除法运算或尝试从字符串中得出数字(实际上不包含数字)时可以得到NaN
.当我可以得到NaN
时,还有其他情况吗?特别是-是否可以通过乘法得到它?
From my experience I know, that I can get NaN
when doing some division or when trying to make a number out of string, when it actually does not contain a number. Are there any other situations, when I can get a NaN
. In particular -- is it possible to get it from multiplication?
这是我在PhoneGap应用程序中使用的一段代码:
This is a piece of code, that I use in my PhoneGap application:
var g = 9.80665;
acceleration.x = (acceleration.x * g).toFixed(2);
acceleration.y = (acceleration.y * g).toFixed(2);
acceleration.z = ((acceleration.z + 1) * g).toFixed(2);
acceleration
是基础PhoneGap对象,我几乎不敢相信它包含一个字符串或任何其他值(除float以外)可能会导致NaN
.
An acceleration
is a base PhoneGap object and I can hardly believe, that it contains a string or any other value, except float, that could result in a NaN
.
但是,在某些情况下(在某些特定设备上),我得到的是NaN
.
However, in some certain situations (on some specific devices) I'm getting a NaN
out of above.
使用以下代码保护"上述值对我来说不是问题:
It isn't a problem for me to "secure" above values with a code like this:
acceleration.x = (parseFloat(acceleration.x) || 0) + ' m/s\u00b2';
acceleration.y = (parseFloat(acceleration.y) || 0) + ' m/s\u00b2';
acceleration.z = (parseFloat(acceleration.z) || 0) + ' m/s\u00b2';
但是,我真的很好奇,什么时候以及为什么只需做一些值的乘积就可以获得NaN
?
But, I'm really curious, when and why I can get a NaN
after doing just a multiply of some values?
BTW: I've read this at MDN, as good as many related answers here at Stack Overflow, but to brought me no help or answer to my question.
推荐答案
将数字与无法转换为数字的内容相乘会得到NaN.
You'll get a NaN when multiplying a number with something that can't be converted to a number.
1 * '100' // 100 because '100' will be converted to 100
1 * '' // 0 because '' will be converted to 0
1 * 'ten' // NaN because 'ten' can't be converted to a number
1 * [] // 0 because [] converted to number will be 0
1 * [123] // 123 because [] will be 123
1 * ['ten'] // NaN
1 * {} // NaN
1 * true // 1 because true will be 1
1 * false // 0
1 * null // 0
1 * undefined // NaN, undefined can't be converted to number
1 * function(){} // NaN
函数'isNaN'检查表达式是否可以转换为数字或不能转换为数字.您需要检查两个数字的乘积,以确认这两个数字都是可以避免错误的数字.
The function 'isNaN' checks if the expression can be converted to a number o not. You culd check both numbers of the multiplication to confirm that both are numbers to avoid errors.
为了完整起见,要知道变量是否完全是NaN,必须将其与自身进行比较:
For the sake of completeness, to know if a variable is exactly NaN you must compare it with itself:
var a = NaN;
if (a != a) console.log('a is NaN');
发生这种情况是因为NaN被定义为与包括自己在内的所有事物都不相等.
It happens because NaN is defined to be unequal to everything, including itself.
这篇关于在Javascript中,什么时候以及为什么数字乘以NaN,然后求值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!