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
语句似乎是错误的。
在我看来,仅仅为了使用 else 部分而设置 if/else 语句是错误的...
只要否定你的条件,你就会得到
else
中的 if
逻辑:
if (!(id in tutorTimes)) { ... }
我个人觉得
if (id in tutorTimes === false) { ... }
比
更容易阅读if (!(id in tutorTimes)) { ... }
但是两者都会起作用。
正如 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)) { ... }
两种快速的可能性:
if(!('foo' in myObj)) { ... }
或
if(myObj['foo'] === undefined) { ... }
您可以将条件设置为 false
if ((id in tutorTimes === false)) { ... }
if(!tutorTimes[id]){ ./*do xx */.. }