方法一
let a = [] function isEmptyObject(obj) { // 校验是否为对象且不为 null if (typeof obj !== "object" || obj === null) { return false; } return Object.keys(obj).length === 0 && obj.constructor === Object; } console.log(isEmptyObject(a)) // true 如果传入的参数可能不是对象(如 null、undefined 或其他类型),需要先进行类型校验 obj.constructor === Object 是为了确保传入的是普通对象(而非数组、null 或继承对象)
方法二
let a = {} function isEmptyObject(obj) { return JSON.stringify(obj) === '{}' } console.log(isEmptyObject(a)) // true 如果对象包含 undefined、Symbol 或函数类型的属性,这些属性会被 JSON.stringify() 忽略,可能导致误判。 不适用于有循环引用的对象。
