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-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)

错误类型

TypeError

什么地方出错了?

出现了与期望不符的类型。这个错误常常由undefinednull 值引起。

此外,某些方法,例如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

解决方法

要解决值为undefinednull 的空指针问题,你可以首先测试值是否为undefinednull

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.}

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp