javascript - 为什么 'NaN' 和 'Undefined' 不是 JavaScript 中的保留关键字?

标签 javascript keyword

我们可以做到:

NaN = 'foo'

还有

undefined = 'foo'

为什么它们不是保留关键字?

  1. 我认为应该实现它,以确保当我们正在寻找一个 number 时,它是一个 number :)

  2. 如果我们应该使用 IsNaN()typeof,为什么需要 NaNundefined

最佳答案

我不能告诉你为什么,但是undefinedNaN 实际上是全局对象的属性:

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 of undefined 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/

相关文章:

java - 如何在 JPQL 中转义 SQL 关键字

java - 如何聚类搜索引擎关键词?

c++ - C++ 'new' 关键字和 C

javascript - 事件上的 JQuery 加载脚本(单击)

javascript - 检查是否已选择输入文件?

java - Java 中具有抽象方法签名的可见性修饰符

python - Tkinter-SyntaxError : non-keyword arg after keyword arg

javascript - 在 niceScroll Js 中禁用垂直滚动

javascript - 如何在 Angular 8 中使用 jasmine 模拟回调函数来测试 promise

javascript - 使用通过 ember-cli 创建的应用程序获取 "Uncaught Error: Assertion Failed: Ember Views require jQuery between 1.7 and 2.1"