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)