1

isNaN 与 Number.isNaN 的区别

 2 years ago
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.
neoserver,ios ssh client

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

参考文档:

  1. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isNaN
  2. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK