此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
TypeError: "x" is (not) "y"
JavaScript 异常“x is (not)y”在出现与期望不符的类型(通常为意外获得的undefined 或null 值)时被抛出。
In this article
消息
TypeError: Cannot read properties of undefined (reading 'x') (V8-based)TypeError: "x" is undefined (Firefox)TypeError: "undefined" is not an object (Firefox)TypeError: undefined is not an object (evaluating 'obj.x') (Safari)TypeError: "x" is not a symbol (V8-based & Firefox)TypeError: Symbol.keyFor requires that the first argument be a symbol (Safari)
错误类型
什么地方出错了?
出现了与期望不符的类型。这个错误常常由undefined 或null 值引起。
此外,某些方法,例如Object.create() 或Symbol.keyFor(),要求必须提供特定类型的参数。
示例
>错误情形
js
// undefined and null cases on which the substring method won't workconst foo = undefined;foo.substring(1); // TypeError: foo is undefinedconst foo = null;foo.substring(1); // TypeError: foo is null// Certain methods might require a specific typeconst foo = {};Symbol.keyFor(foo); // TypeError: foo is not a symbolconst foo = "bar";Object.create(foo); // TypeError: "foo" is not an object or null解决方法
要解决值为undefined 或null 的空指针问题,你可以首先测试值是否为undefined 或null。
js
if (foo !== undefined && foo !== null) { // Now we know that foo is defined, we are good to go.}或者,你如果能确定foo 的值不会是其他的假值(如:"" 或0),或者排除这些情况不是问题,那你可以简单地测试其是否为真。
js
if (foo) { // Now we know that foo is truthy, it will necessarily not be null/undefined.}