我们可以做到:
NaN = 'foo'
还有
undefined = 'foo'
为什么它们不是保留关键字?
我认为应该实现它,以确保当我们正在寻找一个
number
时,它是一个number
:)如果我们应该使用
IsNaN()
或typeof
,为什么需要NaN
或undefined
?
最佳答案
我不能告诉你为什么,但是undefined
和NaN
实际上是全局对象的属性:
15.1.1 Value Properties of the Global Object
15.1.1.1 NaN
The value of NaN is NaN (see 8.5). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
(...)
15.1.1.3 undefined
The value ofundefined
is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
值 undefined
(NaN
) 和对应的属性有区别。
您可能会注意到 [[Writable]]: false
。我不确定这是否是 ES5 中的新功能(并且可能不会被所有浏览器采用),但在较新的浏览器中(在 Firefox 6 中测试过),为 undefined
分配一个新值没有效果:
[12:28:15.090] < undefined = "foo"
[12:28:15.093] > "foo"
[12:28:19.882] < undefined
[12:28:19.883] > undefined
因此,尽管您似乎可以分配一个新值,但实际上您不能。
Why they are not reserved keywords?
不确定是否有特定原因不让它们成为保留关键字,但决定反对。语言仍然有效。您无法覆盖这些值,所以没关系。
测试数字是否为 NaN
的唯一方法是无论如何都使用 isNaN()
。
关于javascript - 为什么 'NaN' 和 'Undefined' 不是 JavaScript 中的保留关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7173773/