TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript 编辑

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: Invalid operand to 'in' (Edge)
TypeError: right-hand side of 'in' should be an object, got 'x' (Firefox)
TypeError: cannot use 'in' operator to search for 'x' in 'y' (Firefox, Chrome)

Error type

TypeError

What went wrong?

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

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

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

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

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

The operand can't be null or undefined

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

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

The in operator always expects an object.

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

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

Searching in arrays

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.

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

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:39 次

字数:4073

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文