const a = null
const b = undefined
console.log(!a) // true
console.log(!b) // true
復(fù)制代碼
判斷是否為 {}
這里的空對(duì)象指的是對(duì)象是存在的js判斷元素是否為空,但是里面沒(méi)有任何屬性和方法。
常用解決方案
通過(guò)ES6語(yǔ)法 .keys() 進(jìn)行判斷
const a = {
name: 'a'
}
const b = {}
console.log(Object.keys(a).length === 0) // false
console.log(Object.keys(b).length === 0) // true
復(fù)制代碼
const a = {
name: 'a'
}

const b = {}
console.log(JSON.stringify(a) === '{}') // false
console.log(JSON.stringify(b) === '{}') // true
復(fù)制代碼
const a = {
name: 'a'
}
const b = {}
console.log(Object.getOwnPropertyNames(a).length === 0) // false
console.log(Object.getOwnPropertyNames(b).length === 0) // true
復(fù)制代碼
特殊情況
當(dāng)對(duì)象的 key 為 () 數(shù)據(jù)類型的時(shí)候,以上方案是否還適用呢?
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
復(fù)制代碼
每一個(gè)都是返回 truejs判斷元素是否為空,所以結(jié)果是錯(cuò)誤的。a 并非空對(duì)象。
那么在 作為key的時(shí)候我們可以考慮使用另外一種方法
s
console.log(Object.getOwnPropertySymbols(a).length === 0) // false
復(fù)制代碼
最終解決方案
1.結(jié)合 s 和
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
復(fù)制代碼
.()
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
復(fù)制代碼