在JavaScript中是否有任何类型的“not in”操作符来检查对象中是否存在属性?我在谷歌或Stack Overflow周围找不到任何关于这个的东西。下面是我正在做的一小段代码,我需要这种功能:

var tutorTimes = {};

$(checked).each(function(idx){
  id = $(this).attr('class');

  if(id in tutorTimes){}
  else{
    //Rest of my logic will go here
  }
});

如你所见,我将把所有东西都放到else语句中。在我看来,为了使用else部分而设置if-else语句似乎是错误的。


对我来说,设置一个if/else语句只是为了使用else部分似乎是错误的…

只要对你的条件求反,你就会得到if语句中的else逻辑:

if (!(id in tutorTimes)) { ... }

两个简单的可能性:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

正如Jordão已经说过的,否定它:

if (!(id in tutorTimes)) { ... }

注意:上面的测试是否tutorTimes有一个属性,其名称指定为id,位于原型链的任何位置。例如tutorTimes中的valueOf返回true,因为它是在Object.prototype中定义的。

如果你想测试一个属性在当前对象中是否不存在,使用hasOwnProperty:

if (!tutorTimes.hasOwnProperty(id)) { ... }

或者如果你可能有一个键是hasownproperty,你可以使用这个:

if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }

我个人认为

if (id in tutorTimes === false) { ... }

更容易阅读

if (!(id in tutorTimes)) { ... }

但两者都可以。

您可以将条件设置为false

if ((id in tutorTimes === false)) { ... }

if(!tutorTimes[id]){./*do xx */..}