关于javascript:如何将if语句中的空对象处理为false?

How to handle empty object in if statement as false?

本问题已经有最佳答案,请猛点这里访问。

我今天偶然发现这个案子

1
2
3
if ({}) {
  // This is returned as empty object is true
}

因此,需要找出一种方法,其中{}是假的,尝试在我传递给if语句的对象上调用.length,但这不起作用。


您可以使用object.keys()方法来实现这一点。

从Mozilla的文档中:

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

1
2
3
4
5
6
7
if (Object.keys({}).length) {
  console.log('Object is not Empty');
} else {
  console.log('Object is Empty');
}

console.log(Object.keys({}).length);


您可以尝试使用:

1
Object.keys(obj).length === 0;