NaN你都未必懂,花五分钟让你懂得不能再懂

开发 前端
NaN全称是Not-A-Number,不是一个数字。在 JavaScript 中,整数和浮点数都统称为 Number 类型。

[[431097]]

NaN和Number.NaN

NaN全称是Not-A-Number,不是一个数字。在 JavaScript 中,整数和浮点数都统称为 Number 类型。

特点1 typeof是数字

口上说不是一个数字,typeof的值却是number, 口是心非。

ES6之后,Number也多了一个静态属性NaN

  1. typeof NaN // number 
  2. typeof Number.NaN // number 

特点2 我不等于我自己

我否定我自己,也就这家了。硬要说,还有一个+0和 -0

  1. NaN == NaN  // false 
  2. Number.NaN == NaN // false 
  3. NaN === NaN // false 
  4. Number.NaN === NaN  // false 
  5.  
  6. +0 == -0 // true 
  7. Object.is(+0, -0) // fasle 

NaN的描述信息

其是一个值,新的ES标准中, 不可配置,不可枚举。也就是说不可以被删除delete,不可以被改写, 也不可以改写配置。

  1. delete NaN // false 
  2. NaN = 1 // 1 
  3. NaN == 1 // false 
  4.  
  5. delete Number.NaN // false 
  6. Number.NaN = 1 // 1 
  7. Number.NaN == 1 // false 

我们尝试改写:

使用Reflect.defineProperty 而不使用Object.defineProperty,因为前者能准确告诉你是否成功,而后者返回的被定义的对象。

  1. const success =Reflect.getOwnPropertyDescriptor(window, 'NaN'), { 
  2.     writable: true
  3.     configurable: true
  4. }) 
  5. console.log(success) // false 
  6. Reflect.getOwnPropertyDescriptor(window, 'NaN'
  7. // {value: NaN, writable: false, enumerable: false, configurable: false

结果是无法改写,所以不要打他的小心思。

常见的场景

计算, 类型转换是典型的场景

  1. let print = console.log; 
  2. // parseInt  
  3. print(isNaN(parseInt("zz123"))) // true 
  4.  
  5. // parseFloat  
  6. print(isNaN(parseFloat("zz123"))) // true 
  7.  
  8. // 直接Number初始化 
  9. print(isNaN(Number("zz123"))) // true 
  10.  
  11. // 数字运算 
  12. print(isNaN(0 / 0 ))  // true 
  13. print(isNaN( 1 * "zz123" )) // true 
  14. print(Math.sqrt(-1)) // true 

isNaN

isNaN() 是一个全局方法。

其本质是检查 toNumber 返回值, 如果是NaN,就返回 true,反之返回 false 。

可以简化为语义:

  1. Number.isNaN =  function (val){ 
  2.    return Object.is(Number(val), NaN);  

toNumber 方法, 大致的逻辑如下:

le 15: ToNumber Conversions

Argument Type Result
Undefined Return NaN.
Null Return +0𝔽.
Boolean If argument is true, return 1𝔽. If argument is false, return +0𝔽.
Number Return argument (no conversion).
String Return ! StringToNumber(argument).
Symbol Throw a TypeError exception.
BigInt Throw a TypeError exception.

关于对象的转换是:

1. Let primValue be ? ToPrimitive(argument, number).

2. Return ? ToNumber(primValue).

简单翻译就是先获取原始类型的值,再转为Number。

取原值,也会根据条件执行不同的方法。

最优先调用 Symbol.toPrimitive, 如果存在

根据条件决定是先调用 valueOf 还是toString

对象这里就比较有意思了, 看下面的例子, valueOf的返回,可以直接影响isNaN的值。

  1. let print = console.log; 
  2. var person = { 
  3.     age: 10, 
  4.     name"tom"
  5.     valueOf(){ 
  6.         return this.name  
  7.     } 
  8. print(isNaN(person))  // true 
  9.  
  10.  
  11. let print = console.log; 
  12. var person = { 
  13.     age: 10, 
  14.     name"tom"
  15.     valueOf(){ 
  16.         return this.age  
  17.     } 
  18. print(isNaN(person))  // false 

常规例子:

  1. let print = console.log; 
  2. print(isNaN("123")) //false 
  3. print(isNaN('zz123')) //true 
  4. print(isNaN(NaN)) //true 

isNaN是可以被删除的,但是不可被枚举:

  1. delete isNaN // true 
  2. typeof // undefined 
  3.  
  4. isNaN = 1  // 1 
  5. isNaN == 1  //true 

属性描述信息:

Number.isNaN

判断一个值是否是数字,并且值等于NaN.

ES标准的描述:

  1. If Type(number) is not Number, return false
  2. If number is NaN, return true
  3. Otherwise, return false

所有可以语义化为:

  1. Number.isNaN = function(val){ 
  2.    if(typeof val !== "number"){ 
  3.        return false 
  4.    } 
  5.    return Object.is(val, NaN); 

demo:

  1. let print = console.log; 
  2.  
  3. print(Number.isNaN(NaN))  // true 
  4. print(Number.isNaN("123")) //false 

isNaN和Number.isNaN的区别

Number.isNaN是严格判断, 必须严格等于NaN。是不是NaN这个值

isNaN是通过内部的 toNumber 转换结果来判定的。Number转换的返回值是不是NaN

Number.isNaN是ES6的语法,固然存在一定的兼容性问题。

Object.is

ES6标准新增方法,用于判断两个值是否属于同一个值,其能准确的判断NaN。

  1. let print = console.log; 
  2.  
  3. print(Object.is(NaN, NaN)); // true 
  4. print(Object.is("123", NaN)) // false 

严格判断NaN汇总

四种,2种ES6, 2种ES5。

  1. Number.isNaN(NaN) // true 
  2. Number.isNaN(1) // false 

Object.is (ES6)

  1. function isNaNVal(val){ 
  2.     return Object.is(val, NaN); 
  3. isNaNVal(NaN) // true 
  4. isNaNVal(1) // false 

自身比较 (ES5)

最为简单的一种方式。

  1. function isNaNVal(val){ 
  2.     return val !== val; 
  3. isNaNVal(NaN) // true 
  4. isNaNVal(1) // false 

typeof + NaN (ES5)

这是MDN推荐的垫片,有些兼容低版本的库就是这么实现的, 也是ES标准的精准表达

  1. function isNaNVal(val){ 
  2.     return typeof val === 'number' && isNaN(val) 

综合的垫片

  1. if(!("isNaN" in Number)) { 
  2.     Number.isNaN = function (val) { 
  3.       return typeof val === 'number' && isNaN(val) 
  4.     } 

深究数组的indexOf与includes

三心酱在50个JS高级知识点有提到 includes能识别 NaN, 我们继续来一看究竟。

  1. var arr=[NaN]; 
  2. arr.indexOf(NaN) // -1 
  3. arr.includes(NaN) // true 

includes

我们深入规范看一看:

ES标准的Array.prototype.includes 比较值相等调用的是内部的 SameValueZero ( x, y )方法,其会检查值第一值是不是数字,如果是数字,调用的是 Number::sameValueZero(x, y), 其具体比较步骤:

  1. 1. If x is NaN and y is NaN, return true
  2.  
  3. 2. If x is +0?? and y is -0??, return true
  4.  
  5. 3. If x is -0?? and y is +0??, return true
  6.  
  7. 4. If x is the same Number value as y, return true
  8.  
  9. 5. Return false

其先对NaN进行了比较,所以能检查NaN, 这里还有一个额外信息,比较的时候+0和-0是相等的, 要区分+0和-0还得用Object.is

indexOf

ES标准中 Array.prototype.indexOf 值比较调用的是IsStrictlyEqual(searchElement, elementK), 其如果检查到第一个值为数字,调用的 Number::equal(x, y).

其比对逻辑

  1. 1. If x is NaN, return false. 2. If y is NaN, return false. 3. If x is the same Number value as y, return true. 4. If x is +0𝔽 and y is -0𝔽, return true. 5. If x is -0𝔽 and y is +0𝔽, return true
  2. 6. Return false

可以看到,任何一个为NaN,就直接返回false,必然不能严格的检查NaN.

Number::sameValueZero 和 Number::sameValue

区别

在上个章节我们提到了,Array.prototype.includes值的比较实用的是 Number::sameValueZero , 突出了Zero, Zero是什么,是0啊,也就是说对0进行了特殊的处理。

对应的还要一个 Number::sameValue 方法, 一起看看:

可以看出Number::sameValueZero 不区分+0 -0, Number::sameValue 则区分。

  1. Object.is(+0, -0) // false, 区分+0,-0 
  2. [-0].includes(+0) // true,不区分+0,-0 

BigInt::sameValue和 BigInt:samgeValueZero

图片可以看出,除了Number有, BigInt也有相似的比较。

这两个方法的主要应用场景也就是 Object.is 和 Array.prototype.includes。

再猜猜下面的结果:

  1. Object.is(BigInt(+0),BigInt(-0)) 
  2. Object.is(-0n,0n) 
  3. Object.is(-0,0) 
  4. [BigInt(+0)].includes(BigInt(-0)) 

3

2

1

结果,不如你所愿:

  1. Object.is(BigInt(+0),BigInt(-0))   // true 
  2. Object.is(-0n,0n) // true 
  3. Object.is(-0,0) // false 
  4. [BigInt(+0)].includes(BigInt(-0))  // false 

哈哈,更多细节 BigInt::equal ( x, y ):

核心解释:

BigInt::sameValue ( x, y ) 调用 BigInt::equal ( x, y )

  1. BigInt::equal ( x, y ) 
  2. 1. If ℝ(x) = ℝ(y), return true; otherwise return false

而R(x)是啥玩意

  1. 从 Number 或 BigInt x 到数学值的转换表示为“ x 的数学值”或 R(x)。+ 0F 和-0F的数学值为0 

简单的结论:

  • Number区分+0,- 0
  • BitInt不区分

BigInt::sameValue和 BigInt:samgeValueZero有什么区别呢?

用一张图,更好解释:

没有区别,更合理的解释是什么呢??

小结

indexOf是ES5甚至更早的产物,includes是ES6的产物。高级产物向着更合理化的方向发展,合情合理。

至于为什么不升级indexOf呢,历史包袱吧,以前的代码总不能让其产生意外效果吧。

 

责任编辑:武晓燕 来源: 云的程序世界
相关推荐

2017-07-12 09:54:33

深度学习AI 人工智能

2009-11-05 10:56:31

WCF通讯

2021-03-04 09:26:57

微服务架构数据

2021-11-07 23:46:32

MySQLSQL索引

2020-11-09 09:59:50

Ajax技术

2021-11-11 15:03:35

MySQLSQL索引

2020-12-08 10:02:25

RESTfulAPI开发

2024-02-21 21:19:18

切片Python语言

2009-11-06 16:05:37

WCF回调契约

2020-11-06 08:54:43

Vue 3.0函数代码

2015-11-12 10:32:40

GitHub控制系统分布式

2017-06-07 18:40:33

PromiseJavascript前端

2009-10-29 11:39:52

ADO.NET连接池

2022-03-18 15:41:29

原子化服务HarmonyOS鸿蒙

2022-03-08 08:39:22

gRPC协议云原生

2017-12-19 10:10:47

2023-12-05 15:24:46

2023-07-15 18:26:51

LinuxABI

2021-03-24 10:58:08

Vuesrc前端

2015-12-03 14:10:26

systemd容器Linux
点赞
收藏

51CTO技术栈公众号