有没有一个“不在”? JavaScript 中的运算符用于检查对象属性?
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
语句中。在我看来,仅仅为了使用 else
部分而设置 if
–else
语句似乎是错误的。
Is there any sort of "not in" operator in JavaScript to check if a property does not exist in an object? I couldn’t find anything about this around Google or Stack Overflow. Here’s a small snippet of code I’m working on where I need this kind of functionality:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
As you can see, I’d be putting everything into the else
statement. It seems wrong to me to set up an if
–else
statement just to use the else
portion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需否定您的条件,您就会在
ifelse
逻辑代码>:Just negate your condition, and you'll get the
else
logic inside theif
:就我个人而言,我发现
比这更容易阅读
,但两者都可以工作。
Personally I find
easier to read than
but both will work.
正如Jordão已经说过的,直接否定它:
注意:上面的测试是否tutorTimes在原型链中任何地方有一个在id中指定名称的属性。例如,tutorTimes 中的“valueOf”返回 true,因为它是在 Object.prototype 中定义的。
如果您想测试当前对象中是否不存在某个属性,请使用 hasOwnProperty:
或者如果您可能有一个 hasOwnPropery 密钥,您可以使用此:
如果您的环境支持 ECMA-292 2022 年 7 月,您可以使用
Object.prototype.hasOwnProperty
的便捷替代方案 Object.hasOwn:As already said by Jordão, just negate it:
Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example
"valueOf" in tutorTimes
returns true because it is defined in Object.prototype.If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
Or if you might have a key that is hasOwnPropery you can use this:
If your environment supports ECMA-292 from July 2022, you can use the convenient alternative to
Object.prototype.hasOwnProperty
Object.hasOwn:两种快速的可能性:
或者
Two quick possibilities:
or
你可以将条件设置为 false
you can set the condition to be false
可读性不太好,但一个快速的简写可能是:
当使用 XOR 进行运算时,
false
和true
被转换为0
和1分别。因此结果相反。
not very readable but a quick short hand could be:
when doing operation with XOR,
false
andtrue
got converted into0
and1
respectively. hence that reverse the result.