在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
在AJAX请求之后,有时我的应用程序可能会返回一个空对象,例如:
var a = {};
我该如何检查是否是这种情况?
当前回答
您可以使用Undercore.js。
_.isEmpty({}); // true
其他回答
这里有一个快速、简单的函数:
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
我的看法:
函数isEmpty(obj){return Object.keys(obj).length==0;}变量a={a: 1中,b: 2个}变量b={}console.log(isEmpty(a));//假的console.log(isEmpty(b));//真的
只是,我认为目前并不是所有浏览器都实现Object.keys()。
if(Object.getOwnPropertyNames(obj).length === 0){
//is empty
}
看见http://bencollier.net/2011/04/javascript-is-an-object-empty/
尝试解构
const a = {};
const { b } = a;
const emptryOrNot = (b) ? 'not Empty' : 'empty';
console.log(emptryOrNot)
警告当心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 {}