繁体   English   中英

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

[英]Is there a “not in” operator in JavaScript for checking object properties?

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
  }
});

如您所见,我会将所有内容都放入else语句中。 在我看来,为了使用else部分而设置ifelse语句似乎是错误的。

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

只是否定了你的病情,你会得到else的内部逻辑if

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

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

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

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

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

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

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

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

个人觉得

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

比阅读更容易

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

但两者都会起作用。

两种快速的可能性:

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

或者

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

您可以将条件设​​置为 false

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

if (!tutorTimes.includes(I'd)) { ... }

我知道这是旧的,但这是另一个看起来不错的选择。

if (!tutorTimes[id]) {...}

与重新分配undefined似的陷阱

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM