javascript 类型错误:无效的 'in' 操作数 obj

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20210529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:00:48  来源:igfitidea点击:

TypeError: invalid 'in' operand obj

javascriptjquery

提问by user2814799

       json= new Gson().toJson(name);

where name is of type string.

其中 name 是字符串类型。

I am getting error saying "TypeError: invalid 'in' operand obj "

我收到错误消息“类型错误:无效的‘in’操作数 obj”

error is in the given part of java script

错误在java脚本的给定部分

 return type === "array" || type !== "function" &&
     ( length === 0 ||
     typeof length === "number" && length > 0 && ( length - 1 ) in obj );

I have also tried

我也试过

   response=JSON.parse(response); 

which is not working.

这是行不通的。

采纳答案by Grundy

by link In operatoryou can see that

通过链接在操作员中,您可以看到

The in operator returns true if the specified property is in the specified object.

如果指定的属性在指定的对象中,则 in 运算符返回 true。

in your code ( length - 1 ) in objyou try checking that property (length - 1)that numeric in your obj

在您的代码中,( length - 1 ) in obj您尝试检查(length - 1)obj 中的数字属性

I think objis a string, so it has the lengthproperty, but does not have numeric properties, so you must catch this case

我认为obj是 a string,所以它有length属性,但没有数字属性,所以你必须抓住这种情况

回答by Fred

I closed the code "( length - 1 ) in obj" between parentheses.

我在括号之间关闭了代码“(length - 1) in obj”。

return type === "array" || type !== "function" &&
     ( length === 0 ||
     typeof length === "number" && length > 0 && (( length - 1 ) in obj) );

That's working fine for me.

这对我来说很好用。

回答by razzbee

In my case the object was not empty but I needed to add double quotes on the object's key , example :

在我的情况下,对象不为空,但我需要在对象的键上添加双引号,例如:

obj = {params : "paramsInputPreData"}

The Above will produce an error but the one below was okay :

上面的会产生错误,但下面的没问题:

obj = {"params" : "paramsInputPreData"}

so for me the key needed to be quoted as "params"

所以对我来说,关键需要被引用为“参数”

Hope it helps someone

希望它可以帮助某人

回答by zygimantus

When you have this error, you need to check the type of your variables, etc., you can always do something like this:

当你遇到这个错误时,你需要检查你的变量的类型等,你总是可以这样做:

if (typeof x == 'string' || typeof x == 'number') { ... }