欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

JS的每日提示:如何检测一个对象是否为空

最编程 2024-08-12 15:24:12
...

如何判断JS对象是不是为空

这里的空对象指的不是 nullundefined

如果要判断是否为 nullundefined,通过非空判断即可.

const a = null
const b = undefined
console.log(!a) // true
console.log(!b) // true

判断是否为 {}

这里的空对象指的是对象是存在的,但是里面没有任何属性和方法。

常用解决方案

  • Object.keys()

通过ES6语法 Object.keys() 进行判断

const a = {
  name: 'a'
}
const b = {}
console.log(Object.keys(a).length === 0) // false
console.log(Object.keys(b).length === 0) // true
  • JSON.stringify()
const a = {
  name: 'a'
}
const b = {}
console.log(JSON.stringify(a) === '{}') // false
console.log(JSON.stringify(b) === '{}') // true
  • Object.getOwnPropertyNames()
const a = {
  name: 'a'
}
const b = {}
console.log(Object.getOwnPropertyNames(a).length === 0) // false
console.log(Object.getOwnPropertyNames(b).length === 0) // true

特殊情况

当对象的 key 为 Symbol() 数据类型的时候,以上方案是否还适用呢?

const a = { [Symbol()]: 'a' }

console.log(a) // { [Symbol()]: 'a' }
console.log(JSON.stringify(a) === '{}') // true
console.log(Object.keys(a).length === 0) // true
console.log(Object.getOwnPropertyNames(a).length === 0) // true

每一个都是返回 true,所以结果是错误的。a 并非空对象。

那么在 Symbol 作为key的时候我们可以考虑使用另外一种方法

getOwnPropertySymbols

console.log(Object.getOwnPropertySymbols(a).length === 0) // false

最终解决方案

1.结合 getOwnPropertySymbolsgetOwnPropertyNames

const a = { [Symbol()]: 'a' }
const b = { a: 'a' }
const c = {}

console.log(Object.getOwnPropertyNames(a).length === 0 && Object.getOwnPropertySymbols(a).length === 0) // false
console.log(Object.getOwnPropertyNames(b).length === 0 && Object.getOwnPropertySymbols(b).length === 0)  // false
console.log(Object.getOwnPropertyNames(c).length === 0 && Object.getOwnPropertySymbols(c).length === 0)  // true

  1. Reflect.ownKeys()
const a = { [Symbol()]: 'a' }
const b = { a: 'a' }
const c = {}
console.log(Reflect.ownKeys(a).length === 0) // false
console.log(Reflect.ownKeys(b).length === 0) // false
console.log(Reflect.ownKeys(c).length === 0) // true

推荐阅读