JavaScript: what is NaN, Object or primitive?

空扰寡人 提交于 2020-02-27 23:11:51

问题


what is NaN, Object or primitive?

NaN - Not a Number


回答1:


NaN is a primitive Number value. Just like 1, 2, etc.




回答2:


It's a primitive. You can check in a number of ways:

  • typeof NaN gives "number," not "object."

  • Add a property, it disappears. NaN.foo = "hi"; console.log(NaN.foo) // undefined

  • NaN instanceof Number gives false (but we know it's a number, so it must be a primitive).

It wouldn't really make sense for NaN to be an object, because expressions like 0 / 0 need to result in NaN, and math operations always result in primitives. Having NaN as an object would also mean it could not act as a falsey value, which it does in some cases.




回答3:


NaN is a property of the global object.

The initial value of NaN is Not-A-Number — the same as the value of Number.NaN. In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

It is rather rare to use NaN in a program. It is the returned value when Math functions fail (Math.sqrt(-1)) or when a function trying to parse a number fails (parseInt("blabla")).

Reference



来源:https://stackoverflow.com/questions/10498511/javascript-what-is-nan-object-or-primitive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!