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

var a = {};

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


当前回答

我们可以通过处理null或undefined检查来检查vanilla js,如下所示,

函数isEmptyObject(obj){回来obj&&Object.keys(obj).length==0&&obj.constructor==对象;}//测试isEmptyObject(new Boolean());//假的isEmptyObject(new Array());//假的isEmptyObject(新RegExp());//假的isEmptyObject(new String());//假的isEmptyObject(新数字());//假的isEmptyObject(new Function());//假的isEmptyObject(new Date());//假的isEmptyObject(空);//假的isEmptyObject(未定义);//假的isEmptyObject({});//真的

其他回答

警告当心JSON的限制。

javascript:
  obj={  f:function(){}  };
  alert( "Beware!! obj is NOT empty!\n\nobj = {  f:function(){}  }" + 
               "\n\nJSON.stringify( obj )\n\nreturns\n\n" +
                        JSON.stringify( obj ) );

显示器

    Beware!! obj is NOT empty!

    obj = {  f:function(){}  }

    JSON.stringify( obj )

    returns

    {}

尝试解构

const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)

你最想知道的是,在使用对象之前,它是否有财产。因此,不要询问isEmpty,然后总是检查if(!isEmption(obj))之类的否定,你可以只测试对象是否为null,是否有财产

export function hasProperties(obj): boolean {
  return obj && obj.constructor === Object && Object.keys(obj).length >= 1;
}

完美的故障保护解决方案

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

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

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。

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

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