JavaScript对象是否为空的检测方法

JavaScript对象是否为空的检测方法

技术背景

在JavaScript开发中,经常需要判断一个对象是否为空。这里的“空对象”通常指没有自有属性的对象。准确检测对象是否为空对于代码的逻辑判断和数据处理非常重要。

实现步骤

1. 使用for…in循环结合Object.hasOwn

1
2
3
4
5
6
7
8
function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}

如果还需要区分{}这样的空对象和其他没有自有属性的对象(如Date对象),可以进行额外的类型检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function isEmptyObject(value) {
if (value == null) {
// null or undefined
return false;
}
if (typeof value!== 'object') {
// boolean, number, string, function, etc.
return false;
}
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) {
return false;
}
return isEmpty(value);
}

2. 使用Object.keys()

1
2
3
function isEmpty(obj) {
return Object.keys(obj).length === 0;
}

3. 使用JSON.stringify()

1
2
3
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}

4. 使用第三方库

  • jQuery
1
jQuery.isEmptyObject({}); // true
  • lodash
1
_.isEmpty({}); // true
  • Underscore
1
_.isEmpty({}); // true

核心代码

兼容旧版本的isEmpty函数

1
2
3
4
5
6
7
8
function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
}

最佳实践

从性能方面考虑,基于for…in循环的方法在大多数浏览器中是最快的,而基于JSON.stringify的方法是最慢的。因此,推荐使用以下代码:

1
2
3
4
function isEmpty(obj) { 
for (var x in obj) { return false; }
return true;
}

常见问题

1. Object.keys(obj).length的性能问题

Object.keys(obj).length的复杂度是O(N),因为它会创建一个包含所有属性名的数组,然后获取数组的长度。而使用for…in循环遍历对象的复杂度是O(1)。

2. JSON.stringify的局限性

JSON.stringify在处理包含函数等特殊属性的对象时会有局限性,例如:

1
2
obj = { f: function(){} };
JSON.stringify(obj); // 返回 "{}",但对象实际上不为空

JavaScript对象是否为空的检测方法
https://119291.xyz/posts/2025-05-09.detection-methods-for-empty-javascript-objects/
作者
ww
发布于
2025年5月9日
许可协议