Why does typeof NaN return 'number'?

2018-12-31 09:25发布

Just out of curiosity.

It doesn't seem very logical that typeof NaN is number. Just like NaN === NaN or NaN == NaN returning false, by the way. Is this one of the peculiarities of javascript, or would there be a reason for this?

Edit: thanks for your answers. It's not an easy thing to get ones head around though. Reading answers and the wiki I understood more, but still, a sentence like

A comparison with a NaN always returns an unordered result even when comparing with itself. The comparison predicates are either signaling or non-signaling, the signaling versions signal an invalid exception for such comparisons. The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.

just keeps my head spinning. If someone can translate this in human (as opposed to, say, mathematician) readable language, I would be gratefull.

标签: javascript
20条回答
浪荡孟婆
2楼-- · 2018-12-31 10:04

This is simply because NaN is a property of the Number object in JS, It has nothing to do with it being a number.

查看更多
初与友歌
3楼-- · 2018-12-31 10:06

If using jQuery, I prefer isNumeric over checking the type:

console.log($.isNumeric(NaN));  // returns false
console.log($.type(NaN));       // returns number

http://api.jquery.com/jQuery.isNumeric/

查看更多
登录 后发表回答