JavaScript 中是否有用于检查对象属性的“not in”运算符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7972446/
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
Is there a “not in” operator in JavaScript for checking object properties?
提问by Aaron
Is there any sort of "not in" operator in JavaScript to check if a property does not exist in an object? I couldn't find anything about this around Google or Stack Overflow. Here's a small snippet of code I'm working on where I need this kind of functionality:
JavaScript 中是否有任何类型的“不在”运算符来检查对象中是否不存在属性?我在 Google 或 Stack Overflow 上找不到任何关于此的信息。这是我正在处理需要这种功能的一小段代码:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
As you can see, I'd be putting everything into the elsestatement. It seems wrong to me to set up an if–elsestatement just to use the elseportion.
如您所见,我会将所有内容都放入else声明中。在我看来,为了使用该部分而设置if-else语句似乎是错误的else。
回答by Jord?o
It seems wrong to me to set up an if/else statement just to use the else portion...
设置 if/else 语句只是为了使用 else 部分对我来说似乎是错误的......
Just negate your condition, and you'll get the elselogic inside the if:
只需否定你的条件,你就会得到else里面的逻辑if:
if (!(id in tutorTimes)) { ... }
回答by some
As already said by Jord?o, just negate it:
正如 Jord?o 已经说过的那样,只需否定它:
if (!(id in tutorTimes)) { ... }
Note: The above test if tutorTimes has a property with the name specified in id, anywherein the prototype chain. For example "valueOf" in tutorTimesreturns truebecause it is defined in Object.prototype.
注意:以上测试是否tutorTimes在原型链中的任何位置具有id 中指定的名称的属性。例如"valueOf" in tutorTimes返回true因为它是在Object.prototype 中定义的。
If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
如果要测试当前对象中是否不存在某个属性,请使用 hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Or if you might have a key that is hasOwnProperyyou can use this:
或者,如果您可能有一个hasOwnPropery密钥,您可以使用它:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
回答by Forage
Personally I find
个人觉得
if (id in tutorTimes === false) { ... }
easier to read than
比阅读更容易
if (!(id in tutorTimes)) { ... }
but both will work.
但两者都会起作用。
回答by reedlauber
Two quick possibilities:
两种快速的可能性:
if(!('foo' in myObj)) { ... }
or
或者
if(myObj['foo'] === undefined) { ... }

