在线文档教程
JavaScript
错误 | Errors

Errors: Unexpected type

Errors: Unexpected type

信息

TypeError: "x" is (not) "y" Examples: TypeError: "x" is undefined TypeError: "x" is null TypeError: "undefined" is not an object TypeError: "x" is not an object or null TypeError: "x" is not a symbol

错误类型

TypeError.

哪里出错了?

有一个意想不到的类型。这会产生undefinednull值。

另外,必须提供某些方法,例如Object.create()Symbol.keyFor()需要特定的类型。

示例

无效的情况

// undefined and null cases on which the substring method won't work var foo = undefined; foo.substring(1 // TypeError: foo is undefined var foo = null; foo.substring(1 // TypeError: foo is null // Certain methods might require a specific type var foo = {} Symbol.keyFor(foo // TypeError: foo is not a symbol var foo = 'bar' Object.create(foo // TypeError: "foo" is not an object or null

解决这个问题

例如,要修复空值指针undefinednull值,可以使用typeof运算符。

if (typeof foo !== 'undefined') { // Now we know that foo is defined, we are good to go. }