消息
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
错误类型
什么地方出错了?
出现了与期望不符的类型。 这个错误常常由 null
值引起。
此外,某些方法,例如 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
解决方法
要解决空指针以及 undefined
或 null
值的问题, 你可以使用 typeof 操作符, 例如:
if (typeof foo !== 'undefined') { // Now we know that foo is defined, we are good to go. }