如何在JavaScript中检查对象是否为空

Say you want to check if a value you have is equal to the empty object, which can be created using the object literal syntax:

假设您要检查您拥有的值是否等于空对象,可以使用对象文字语法创建该值:

const emptyObject = {}

How can you do so?

你该怎么做?

Use the Object.entries() function.

使用Object.entries()函数。

It returns an array containing the object’s enumerable properties.

它返回一个包含对象的可枚举属性的数组。

It’s used like this:

它的用法如下:

Object.entries(objectToCheck)

If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.

如果返回一个空数组,则表示该对象没有任何可枚举的属性,这又意味着该对象为空。

Object.entries(objectToCheck).length === 0

You should also make sure the object is actually an object, by checking its constructor is the Object object:

您还应该通过检查其构造函数为Object对象来确保该对象实际上是一个对象:

objectToCheck.constructor === Object

Lodash, a popular library, makes it simpler by providing the isEmpty() function:

Lodash是一个流行的库,它通过提供isEmpty()函数使其变得更简单:

_.isEmpty(objectToCheck)

翻译自: https://flaviocopes.com/how-to-check-object-empty/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值