类型错误:无法使用 'in' 运算符在 'y' 中搜索 'x'

当使用 in 运算符 搜索字符串、数字或其他基本类型时,会发生 JavaScript 异常 "'in' 的右侧应该是一个对象"。它只能用于检查属性是否在对象中。

¥The JavaScript exception "right-hand side of 'in' should be an object" occurs when the in operator was used to search in strings, or in numbers, or other primitive types. It can only be used to check if a property is in an object.

信息

¥Message

TypeError: Cannot use 'in' operator to search for 'x' in 'y' (V8-based & Firefox)
TypeError: right-hand side of 'in' should be an object, got null (Firefox)
TypeError: "y" is not an Object. (evaluating '"x" in "y"') (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

in 运算符 只能用于检查属性是否在对象中。你无法在字符串、数字或其他基本类型中进行搜索。

¥The in operator can only be used to check if a property is in an object. You can't search in strings, or in numbers, or other primitive types.

示例

¥Examples

在字符串中搜索

¥Searching in strings

与其他编程语言(例如 Python)不同,你无法使用 in 运算符

¥Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator.

js
"Hello" in "Hello World";
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'

例如,你将需要使用 String.prototype.includes()

¥Instead you will need to use String.prototype.includes(), for example.

js
"Hello World".includes("Hello");
// true

操作数不能为 null 或未定义

¥The operand can't be null or undefined

确保你正在检查的对象实际上不是 nullundefined

¥Make sure the object you are inspecting isn't actually null or undefined.

js
const foo = null;
"bar" in foo;
// TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome)
// TypeError: right-hand side of 'in' should be an object, got null (Firefox)

in 运算符始终需要一个对象。

¥The in operator always expects an object.

js
const foo = { baz: "bar" };
"bar" in foo; // false

"PI" in Math; // true
"pi" in Math; // false

在数组中搜索

¥Searching in arrays

使用 in 运算符搜索 Array 对象时要小心。in 运算符检查索引号,而不是该索引处的值。

¥Be careful when using the in operator to search in Array objects. The in operator checks the index number, not the value at that index.

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

也可以看看

¥See also