javascript - 为什么分配给 `NaN` 或 `undefined` 会导致 TypeError?

标签 javascript typeerror

A.S.:问题是关于错误的类型,而不是关于现象

"use strict" 如果 NaNundefined 等系统变量发生更改,则会抛出 TypeError。
但为什么是类型错误呢?为什么不是语法错误?


编辑:实际上,这里不是 SyntaxError,因为代码段的语法没有错误。
但错误的根源在于,某些 protected 对象无法手动更改;所以,很可能是访问错误(我知道没有这样的错误)。
那么,为什么访问错误看起来像类型错误?

最佳答案

在 ES5 中,有 6 种不同的 native errors :

  • EvalError

    This exception is not currently used within this specification. This object remains for compatibility with previous editions of this specification.

  • RangeError

    Indicates a numeric value has exceeded the allowable range.

  • ReferenceError

    Indicate that an invalid reference value has been detected.

  • SyntaxError

    Indicates that a parsing error has occurred.

  • TypeError

    Indicates the actual type of an operand is different than the expected type.

  • URIError

    Indicates that one of the global URI handling functions was used in a way that is incompatible with its definition.

在您的情况下,抛出错误是因为您试图为 window.NaN 赋值或 window.undefined ,这是不可写的属性。

在分配新值之前,内部 [[Put]]方法检查 [[CanPut]] ,这将返回 false,因为该属性是不可枚举的。因此 [[Put]] 将抛出。

所以问题是分配的引用(assignment expression 中的左操作数)的可写性不是预期的。然后,在上面的 6 种错误中,最合适的似乎是 TypeError,即使可写性不完全是 type。 .

关于javascript - 为什么分配给 `NaN` 或 `undefined` 会导致 TypeError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37103330/

相关文章:

javascript - 在 CasperJS 中拆分测试文件——与它的逻辑作斗争

python - Pygame 类型错误 : __init__ takes exactly 4 arguments (1 given)

python - "TypeError: ' 设置 ' object is not callable"

json - AngularJS Factory undefined 不是一个函数

javascript - 又一个 'Uncaught TypeError: Cannot call method ' apply ' of undefined '

javascript - 如何使用 For 循环将多个对象写入数组?

javascript - 这是什么意思? "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"

javascript - 使用 javascript 小书签在网页中查找 'old' 的所有实例并将每个实例替换为 'new'

javascript - react : input type "file" ignores `accept` property when you upload files using drag and drop

python - 如何在 Python 中使用键创建字典