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

后端 未结 4 1489
有刺的猬
有刺的猬 2020-12-07 19:35

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 Overflo

相关标签:
4条回答
  • 2020-12-07 19:57

    As already said by Jordão, just negate it:

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

    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:

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

    Or if you might have a key that is hasOwnPropery you can use this:

    if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
    
    0 讨论(0)
  • 2020-12-07 20:12

    It seems wrong to me to set up an if/else statement just to use the else portion...

    Just negate your condition, and you'll get the else logic inside the if:

    if (!(id in tutorTimes)) { ... }
    
    0 讨论(0)
  • 2020-12-07 20:18

    Two quick possibilities:

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

    or

    if(myObj['foo'] === undefined) { ... }
    
    0 讨论(0)
  • 2020-12-07 20:22

    Personally I find

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

    easier to read than

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

    but both will work.

    0 讨论(0)
提交回复
热议问题