TypeError: cannot use 'in' operator to search for 'x' in 'y'
JavaScript 异常 "in 运算符的右侧必须是对象" 发生在使用 in 运算符在字符串、数字或其他原始类型中进行搜索时。它只能用于检查属性是否在对象中。
消息
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)
错误类型
TypeError
哪里出错了?
in 运算符只能用于检查属性是否在对象中。你不能在字符串、数字或其他原始类型中搜索。
示例
在字符串中搜索
与其它编程语言(例如 Python)不同,你不能使用 in 运算符在字符串中搜索。
js
"Hello" in "Hello World";
// TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World'
相反,你需要使用 String.prototype.includes(),例如。
js
"Hello World".includes("Hello");
// true
操作数不能为 null 或 undefined
确保你正在检查的对象不是 null 或 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 运算符总是期望一个对象。
js
const foo = { baz: "bar" };
"bar" in foo; // false
"PI" in Math; // true
"pi" in Math; // false
在数组中搜索
在使用 in 运算符在 Array 对象中搜索时要小心。in 运算符检查的是索引号,而不是该索引处的值。
js
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
3 in trees; // true
"oak" in trees; // false