问题
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?
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);
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
.
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';
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.
回答1:
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
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.
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');
It happens because NaN is defined to be unequal to everything, including itself.
回答2:
Are you sure, the values can never be undefined? The documentation doesn't say so, but I think it might be possible.
http://docs.phonegap.com/en/1.0.0/phonegap_accelerometer_accelerometer.md.html#Acceleration
回答3:
0 * Infinity ----> NaN
at least in Chrome and Firefox.
Infinity
* Infinity
, 3.14159 * Infinity
, and Infinity + Infinity
are well behaved. They are all Infinity
.
Infinity - Infinity
is also NaN
You might think you have no Infinity
s, but a 0.000001/0
will suffice to create one.
来源:https://stackoverflow.com/questions/17718394/when-and-why-number-evaluates-to-nan-after-multiplying-in-javascript