Aar*_*ron 156 javascript properties object operators
JavaScript中是否有任何"not in"运算符来检查对象中是否存在属性?我无法在Google或SO周围找到任何相关信息.这是我正在处理的一小段代码,我需要这种功能:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我会把所有内容都放在else语句中.我只是为了使用else部分来设置if/else语句似乎是错的...
Jor*_*dão 298
我只是为了使用else部分来设置if/else语句似乎是错的...
只是否定你的条件,你将获得以下内容的else逻辑if:
if (!(id in tutorTimes)) { ... }
Run Code Online (Sandbox Code Playgroud)
For*_*age 35
个人觉得
if (id in tutorTimes === false) { ... }
Run Code Online (Sandbox Code Playgroud)
比阅读更容易
if (!(id in tutorTimes)) { ... }
Run Code Online (Sandbox Code Playgroud)
但两者都会起作用。
som*_*ome 31
正如Jordão所说,只是否定它:
if (!(id in tutorTimes)) { ... }
Run Code Online (Sandbox Code Playgroud)
注意:如果tutorTimes 在原型链中的任何位置具有id中指定名称的属性,则上述测试.例如,"valueOf" in tutorTimes返回true,因为它在Object.prototype中定义.
如果要测试当前对象中是否存在属性,请使用hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Run Code Online (Sandbox Code Playgroud)
或者,如果您有一个hasOwnPropery键,您可以使用:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
Run Code Online (Sandbox Code Playgroud)
小智 13
两种快速可能性:
if(!('foo' in myObj)) { ... }
Run Code Online (Sandbox Code Playgroud)
要么
if(myObj['foo'] === undefined) { ... }
Run Code Online (Sandbox Code Playgroud)