isNaN 与 Number.isNaN 的区别
source link: https://foofish.net/JavaScript-isNaN-vs-Number.isNaN.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
1、NaN 是什么
NaN
是一个数值类型,与普通数值如1,2,3 都属于同一类型,但它是一个特殊的数值叫“非数值”,Not a Number。
console.log(typeof(NaN)) // 'number'
什么情况下会得到这个值呢? 有以下几种情况
1、 0/0 会得到 NaN
2、 Infinity/Infinity
3、 无法转换为数值的操作数,例如:parseInt('a')
NaN
与任何值相比较都不相等, 包括NaN与NaN比较两者也不相等。
console.log(NaN===NaN) //false
那如何判断某个变量的值是否为为NaN呢? 答案是使用全局函数 isNaN
或者 Number.isNaN
方法
2、isNaN
isNaN(x)
是全局函数,用来确定一个值值是否为NaN
,只有当参数x的值为NaN或者无法转换为数值的非数值返回True。
isNaN(NaN) // true isNaN('a') // true 字符串 “a” 无法转换为数值 isNaN('1') // false , 字符串“1” 可以转换为数值 1 isNaN("") // false 空字符串可以转换为0, 因为 Number("") == 0, 另外 null, 空格字符串 " ", 空数组[], 只有一个元素的数值数组[1] 或者 ["1"]都可以转换为0, isNaN 都返回false isNAN("123a") // true , 因为 Number("123a") 的结果时NaN
3、Number.isNaN
Number.isNaN(x) 是判断变量值是否为NaN
更为严格的一种方法,只有当x与全局常量NaN具有相同值才返回true。 它不会自动将参数去做数值转换
Number.isNaN("a") // false, 因为字符串a不是NaN,所以返回false Number.isNaN(NaN) // true
4、如何判断是否为数值
最后问题来了, 可以使用 isNaN 或者 Number.isNaN 来判断某个变量的值是否为数值吗? 例如:
if (!isNaN(x)){ console.log("x是数值") // 即时if表达式的值为true,也不能说明x是数值 }
答案肯定不行, 这两个方法的功能是判断是否为NaN
, 因为 isNaN 为 false 时,变量不一定是数值,例如字符串“1”既不是NaN,也不是数值。
要严格判断是否为数值且不是NaN可以表达式
if(typeof x === 'number' && !isNaN(x)){ console.log("x是数值") // 这样x才是真正的数值 }
如果判断是不是整数,其实可以用 Number.isInteger
参考文档:
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isNaN
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
有问题可以扫描二维码和我交流
关注公众号「Python之禅」,回复「1024」免费获取Python资源
Recommend
-
127
Professionals | Community Groups Programs | Google Developers
-
138
dragonzurfer/star master
-
113
HTC to limit number of new smartphones for 2018 Sammi Huang, Taipei; Steve Shen, DIGITIMES Asia Wednesday 27 December 2017
-
116
写在前面 今天在看《JavaScript高级程序设计》的时候,注意到书中特意提到了0.1+0.2=0.30000000000000004这样一个浮点数计算错误的问题,觉得很有意思。平时在工作中对于浮点数了解地并不多,正好最近小组同学也遇到了这个问题,准备来总结
-
88
README.md Special thanks to
-
82
In this Tutorial, we will learn about Kotlin Number types. Following types comes under Kotlin number types: Byte Short Int Long Double Float. Here, Byte, Short, Int and Long are Integer types (non decimal) numbers. Double and Float are Floating...
-
12
The isNaN() function determines whether a value is NaN or not. Note, coercion inside the isNaN function...
-
16
Number.isNaN() - JavaScript | MDN The Number.isNaN() method determines whether the passed value is NaN...
-
3
Checking if a Value is a Number in Javascript with isNaN()Checking if a Value is a Number in Javascript with isNaN()February 6th 202...
-
3
np.isnan(1.0) is False 的结果是 False 作者: ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK