在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:

var a = {};

我该如何检查是否是这种情况?


当前回答

    isEmpty = function(obj) {
      if (obj == null) return true;
      if (obj.constructor.name == "Array" || obj.constructor.name == "String") return obj.length === 0;
      for (var key in obj) if (isEmpty(obj[key])) return true;
      return false;
    }

这将检查字符串、数组或对象(映射)的空性。

用法:

var a = {"a":"xxx","b":[1],"c":{"c_a":""}}
isEmpty(a); // true, because a.c.c_a is empty.
isEmpty("I am a String"); //false

其他回答

Sugar.JS为此提供了扩展对象。代码简洁明了:

创建扩展对象:

a = Object.extended({})

检查尺寸:

a.size()
if(Object.getOwnPropertyNames(obj).length === 0){
  //is empty
}

看见http://bencollier.net/2011/04/javascript-is-an-object-empty/

这里有一个快速、简单的函数:

function isEmptyFunction () {
  for (const i in this) return false
  return true
}

作为getter实现:

Object.defineProperty(Object.prototype, 'isEmpty', { get: isEmptyFunction })

console.log({}.isEmpty) // true

作为单独的功能实现:

const isEmpty = Function.prototype.call.bind(isEmptyFunction)

console.log(isEmpty({})) // true

完美的故障保护解决方案

我认为第一个被接受的解决方案在大多数情况下都有效,但不是故障保护。

更好的故障安全解决方案将是。

function isEmptyObject() { 
  return toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;
}

或ES6/7

const isEmptyObject = () => toString.call(obj) === "[object Object]" 
  && Object.keys(obj).length === 0;

使用这种方法,如果obj设置为undefined或null,则代码不会中断。并返回null。

任何类型的值都为空

/* eslint-disable no-nested-ternary */

const isEmpty = value => {
  switch (typeof value) {
    case 'undefined':
      return true;
    case 'object':
      return value === null
        ? true
        : Array.isArray(value)
        ? !value.length
        : Object.entries(value).length === 0 && value.constructor === Object;
    case 'string':
      return !value.length;
    default:
      return false;
  }
};