在JavaScript开发中,特别是在处理AJAX请求返回的数据时,经常会遇到需要判断一个对象是否为空的情况。一个空对象通常指的是没有任何自有属性的对象,例如 var a = {}。准确判断对象是否为空对于程序的逻辑判断和错误处理非常重要。
实现步骤
1. 使用 for...in 循环结合 Object.hasOwn(ECMA 2022+)
1 2 3 4 5 6 7 8
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); }