在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
jQuery在这种情况下具有特殊的函数isEmptyObject():
jQuery.isEmptyObject({}) // true
jQuery.isEmptyObject({ foo: "bar" }) // false
阅读更多信息http://api.jquery.com/jQuery.isEmptyObject/
其他回答
export function isObjectEmpty(obj) {
return (
Object.keys(obj).length === 0 &&
Object.getOwnPropertySymbols(obj).length === 0 &&
obj.constructor === Object
);
}
这包括检查包含符号财产的对象。
Object.keys不检索符号财产。
您可以使用Undercore.js。
_.isEmpty({}); // true
Sugar.JS为此提供了扩展对象。代码简洁明了:
创建扩展对象:
a = Object.extended({})
检查尺寸:
a.size()
我能找到的最佳单线解决方案(已更新):
isEmpty=obj=>!Object.values(obj).filter(e=>类型e!=='undefined').length;console.log(isEmpty({}))//trueconsole.log(isEmpty({a:undefined,b:undefine}))//trueconsole.log(isEmpty({a:undefined,b:void 1024,c:void 0}))//trueconsole.log(isEmpty({a:[undefined,undefined]}))//falseconsole.log(isEmpty({a:1}))//falseconsole.log(isEmpty({a:“”}))//falseconsole.log(isEmpty({a:null,b:undefined}))//false
对于有相同问题但使用jQuery的人,可以使用jQuery.isEmptyObject。