functionisEmpty(obj) { for (const prop in obj) { if (Object.hasOwn(obj, prop)) { returnfalse; } } returntrue; }
如果还需要区分{}这样的空对象和其他没有自有属性的对象(如Date对象),可以进行额外的类型检查:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
functionisEmptyObject(value) { if (value == null) { // null or undefined returnfalse; } if (typeof value!== 'object') { // boolean, number, string, function, etc. returnfalse; } const proto = Object.getPrototypeOf(value); // consider `Object.create(null)`, commonly used as a safe map // before `Map` support, an empty object as well as `{}` if (proto!== null && proto!== Object.prototype) { returnfalse; } returnisEmpty(value); }