消息
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(),需要提供特定的类型。
示例
无效案例
你不能在 undefined 或 null 变量上调用方法。
js
const foo = undefined;
foo.substring(1); // TypeError: foo is undefined
const foo2 = null;
foo2.substring(1); // TypeError: foo2 is null
某些方法可能需要特定类型。
js
const foo = {};
Symbol.keyFor(foo); // TypeError: foo is not a symbol
const foo2 = "bar";
Object.create(foo2); // TypeError: "foo2" 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.
}