Movatterモバイル変換


[0]ホーム

URL:


  1. 給開發者的 Web 技術文件
  2. JavaScript
  3. JavaScript 參考文件
  4. JavaScript 錯誤參考
  5. TypeError: "x" is (not) "y"

此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in EnglishAlways switch to English

TypeError: "x" is (not) "y"

JavaScript 的「x is (not)y」例外會在出現非預期的型別時發生。這通常是非預期的undefinednull 值。

訊息

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)

錯誤類型

TypeError

哪裡出錯了?

出現了非預期的型別。這通常發生在undefinednull 值的情況。

此外,某些方法(例如Object.create()Symbol.keyFor())需要提供特定的型別。

範例

無效的案例

你不能在undefinednull 的變數上呼叫方法。

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

修正問題

為了修正對undefinednull 值進行存取的問題,你可以先測試該值是否為undefinednull

js
if (foo !== undefined && foo !== null) {  // 現在我們知道 foo 已被定義,可以繼續執行。}

或者,如果你確定foo 不會是其他假值(例如""0),或者過濾掉這些情況不成問題,你可以直接測試其真假值。

js
if (foo) {  // 現在我們知道 foo 是真值,所以它必定不是 null/undefined。}

參見

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp