最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Automatic Type Conversion Confusion - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5

Keep 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.

发布评论

评论列表(0)

  1. 暂无评论