JavaScript 中是否有“not in”运算符用于检查对象属性?

问题描述 投票:0回答:6

JavaScript 中是否有任何类型的“not in”运算符来检查对象中是否不存在属性?我在 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
  }
});

如您所见,我会将所有内容都放入

else
语句中。在我看来,仅仅为了使用
if
部分而设置
else
else
语句似乎是错误的。

javascript object properties operators
6个回答
525
投票

在我看来,仅仅为了使用 else 部分而设置 if/else 语句是错误的...

只要否定你的条件,你就会得到

else
中的
if
逻辑:

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

80
投票

我个人觉得

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

更容易阅读
if (!(id in tutorTimes)) { ... }

但是两者都会起作用。


44
投票

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

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

注意:上面测试tutorTimes在原型链中是否有id、anywhere指定名称的属性。例如,

"valueOf" in tutorTimes
返回true,因为它是在Object.prototype中定义的。

如果要测试当前对象中是否不存在某个属性,请使用 hasOwnProperty:

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

或者,如果您可能有一个 hasOwnPropery 的密钥,您可以使用这个:

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

16
投票

两种快速的可能性:

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

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

3
投票

您可以将条件设置为 false

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.