Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

javascript - Is NaN equal to NaN?

parseFloat("NaN")

returns "NaN", but

parseFloat("NaN") == "NaN"

returns false. Now, that's probably a good thing that it does return false, but I don't understand how this is so. Did the JavaScript creators just make this a special case? Because otherwise I can't understand how this returns false.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update 2

New to ECMAScript 6 is the Object.is() function. This is designed to be a further enhancement of the === check. One of the benefits of this new function is that Object.is(NaN, NaN) will now return true. If you're able to utilize ECMAScript 6, then this would be the most readable and consistent solution for you.

Original

The proper way to check this would be:

isNaN(parseInt(variable))

If whatever you're checking is a NaN, that function will return true. This method is built into the JavaScript spec.

Using jQuery

jQuery built in their own isNaN function originally to help counter some discrepancies between browsers, and add some additional checks so their version can be used instead of the one in VanillaJS.

Update for jQuery

After jQuery 1.7, they changed this function to $.isNumeric().

Documentation of the switch

If you take a look at this Stack Overflow question, you'll find plenty of times where isNaN() returns what would intuitively be considered an "incorrect" answer, but is correct by the spec.

One of the big reasons to avoid the vanilla isNaN() is that null will return false, making you think it is a number. However, the jQuery function covers a much larger range of intuitive results.

From their documentation:

As of jQuery 3.0 $.isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers. In all other cases, it returns false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...