Given a JavaScript object, you can check if a property key exists inside its properties using the in
operator.
给定一个JavaScript对象,您可以使用in
运算符检查属性键是否在其属性内。
Say you have a car
object:
假设您有car
用品:
const car = {
color: 'blue'
}
We can check if the color
property exists using this statement, that results to true
:
我们可以使用此语句检查color
属性是否存在,结果为true
:
'color' in car
We can use this in a conditional:
我们可以在有条件的情况下使用它:
if ('color' in car) {
}
Another way is to use the hasOwnProperty()
method of the object:
另一种方法是使用对象的hasOwnProperty()
方法:
car.hasOwnProperty('color')
When inheritance is an important part of your applications structure, the difference is that in
will result true
even for properties inherited by parent objects. hasOwnProperty()
doesn’t. It will only return true
if the object has that property directly - not one of its ancestors.
当继承是应用程序结构的重要部分时,不同之处在于in
即使对于父对象继承的属性, in
也会产生true
。 hasOwnProperty()
没有。 仅当对象直接具有该属性而不是其祖先之一时,它才会返回true
。
I use a fallback mechanism when I want one property and fallback to a default value if that does not exist:
当我需要一个属性时,我使用回退机制;如果该属性不存在,则回退到默认值:
car.brand || 'Ford'
If the brand
property key does not exist on the object, this statement results to the Ford
string.
如果对象上不存在brand
属性键,则此语句将生成Ford
字符串。
翻译自: https://flaviocopes.com/how-to-check-key-exists-javascript/