Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 错误参考
  5. TypeError: invalid 'in' operand "x"

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

TypeError: invalid 'in' operand "x"

错误提示

TypeError: invalid 'in' operand "x" (Firefox)TypeError: Cannot use 'in' operator to search for 'x' in y (Chrome)

错误类型

TypeError

哪里出错了?

in 操作符只可以用来检测对象中是否存在某个属性,而不能用来在字符串、数字或者其他基本类型的数据中进行检索。

示例

在字符串中进行检索

与其他语言不同(如 Python),不能使用in 操作符在字符串中进行检索。

js
"Hello" in "Hello World";// TypeError: invalid 'in' operand "Hello World"

可以使用String.prototype.indexOf() 来代替:

js
"Hello World".indexOf("Hello") !== -1;// true

操作数不能为 null 或者 undefined

确保你将要进行探测的对象不为null 或者undefined.

js
var foo = null;"bar" in foo;// TypeError: invalid 'in' operand "foo"

in 操作符的预期操作数只有对象类型。

js
var foo = { baz: "bar" };"bar" in foo; // false"PI" in Math; // true"pi" in Math; // false

在数组中进行检索

当使用 in 操作符来对Array 对象进行检索的时候一定要特别小心,因为它检测的是索引值而不是位于索引位置的值。

js
var trees = ["redwood", "bay", "cedar", "oak", "maple"];3 in trees; // true"oak" in trees; // false

相关内容

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp