MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

消息

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.
}

相关页面

文档标签和贡献者

标签: 
 此页面的贡献者: yenshen, niaodan2b
 最后编辑者: yenshen,