如何判断JS对象是不是为空
这里的空对象指的不是 null 和 undefined
如果要判断是否为 null或undefined,通过非空判断即可.
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.结合 getOwnPropertySymbols 和 getOwnPropertyNames
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
- 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