pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Errors/Unexpected_type

pt src="/static/client/index.455dc24ca3b6b460.js" type="module">

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

View in English Always 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 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

修正問題

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

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

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

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

參見

pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy