在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
这里有一个快速、简单的函数:
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
其他回答
从jQuery 1.4开始,isEmptyObject()方法检查对象本身的财产和从原型继承的财产(因为它不使用hasOwnProperty)。参数应该始终是一个普通的JavaScript对象,因为其他类型的对象(DOM元素、原始字符串/数字、宿主对象)可能不会在浏览器中提供一致的结果。要确定对象是否为纯JavaScript对象,请使用$.isPlainObject()。
jQuery.isPlainObject({}) // true
jQuery.isPlainObject( "test" ) // false
Jquery api
除了Thevs的回答:
var o = {};
alert($.toJSON(o)=='{}'); // true
var o = {a:1};
alert($.toJSON(o)=='{}'); // false
它是jquery+jquery.json
我能找到的最佳单线解决方案(已更新):
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
我为AJAX调用返回了一个空的JSON响应,在IE8中jQuery.isEmptyObject()没有正确验证。我加了一张额外的支票,似乎能正确地抓住它。
.done(function(data)
{
// Parse json response object
var response = jQuery.parseJSON(data);
// In IE 8 isEmptyObject doesn't catch the empty response, so adding additional undefined check
if(jQuery.isEmptyObject(response) || response.length === 0)
{
//empty
}
else
{
//not empty
}
});
您可以使用lodash库而不是创建一个简单的JS函数。
_.isEmpty({})//真
这将检查数组和对象是否有值并返回布尔值。