admin管理员组文章数量:1332404
Given this script:
var number = NaN;
if (!number) {
alert("yes");
}
alert(number == false);
Why does the first expression `!number
evaluates to true, while the second expression number == false
evaluates to false?
/
Given this script:
var number = NaN;
if (!number) {
alert("yes");
}
alert(number == false);
Why does the first expression `!number
evaluates to true, while the second expression number == false
evaluates to false?
http://jsfiddle/8EWG4/
Share Improve this question asked Oct 29, 2011 at 17:30 helpermethodhelpermethod 62.3k71 gold badges198 silver badges280 bronze badges 1- I'm guessing this has to do with NaN being 'falsey'. – Ivan Commented Oct 29, 2011 at 17:34
4 Answers
Reset to default 5Keep a look in this article: http://www.smashingmagazine./2011/05/30/10-oddities-and-secrets-about-javascript/
There's some tricks about javascript, including informations about NaN:
NaN is a Number
You thought null being an object was ridiculous? Try dealing with the idea of NaN — “not a number” — being a number! Moreover, NaN is not considered equal to itself! Does your head hurt yet?
alert(typeof NaN); //alerts 'Number'
alert(NaN === NaN); //evaluates false
In fact NaN is not equal to anything. The only way to confirm that something is NaN is via the function isNaN().
The ECMAScript specification says so:
x == y
is defined as (11.9.3):
If x is NaN, return false.
And !
calls ToBoolean
(9.2) first (and then returns the opposite):
The result is false if the argument is +0, −0, or NaN; otherwise the result is true
To evaluate a variable is NaN ( not a number ), consider using isNaN(number)
. It will give you correct answer.
From wikipedia - JavaScript syntax, boolean:
When used in a logical context, 0, -0, null, NaN, undefined, and the empty string ("") evaluate as false due to automatic type coercion.
!NaN == true
So, as NaN is coerced to false
, !NaN
evaluates to true
.
However, NaN
is not equal to false
- it is a different type/value.
本文标签: JavaScript Automatic Type Conversion ConfusionStack Overflow
版权声明:本文标题:JavaScript Automatic Type Conversion Confusion - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742279333a2445797.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论