在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语句似乎是错误的。
正如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)) { ... }
正如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)) { ... }