此頁面由社群從英文翻譯而來。了解更多並加入 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)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 & 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 undefinedconst foo2 = null;foo2.substring(1); // TypeError: foo2 is null某些方法可能需要特定的型別。
js
const foo = {};Symbol.keyFor(foo); // TypeError: foo is not a symbolconst foo2 = "bar";Object.create(foo2); // TypeError: "foo2" is not an object or null修正問題
為了修正對undefined 或null 值進行存取的問題,你可以先測試該值是否為undefined 或null。
js
if (foo !== undefined && foo !== null) { // 現在我們知道 foo 已被定義,可以繼續執行。}或者,如果你確定foo 不會是其他假值(例如"" 或0),或者過濾掉這些情況不成問題,你可以直接測試其真假值。
js
if (foo) { // 現在我們知道 foo 是真值,所以它必定不是 null/undefined。}