如何检查JavaScript对象中是否存在密钥

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也会产生truehasOwnProperty()没有。 仅当对象直接具有该属性而不是其祖先之一时,它才会返回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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值