function isEmpty(obj) {return Object.keys(obj).length === 0;}
var a = {a: 1,b: 2}var b = {}
console.log(isEmpty(a)); // falseconsole.log(isEmpty(b)); // true
function isObjectEmpty(object) {var isEmpty = true;for (keys in object) {isEmpty = false;break; // exiting since we found that the object is not empty}return isEmpty;}
例如:
var myObject = {}; // Object is emptyvar isEmpty = isObjectEmpty(myObject); // will return true;
// populating the objectmyObject = {"name":"John Smith","Address":"Kochi, Kerala"};
// check if the object is emptyisEmpty = isObjectEmpty(myObject); // will return false;
Object.prototype.hasOwnProperties = function(){for (var k in this){if ( this.hasOwnProperty(k) ){return true;}}return false;}
下面是一个用法示例:
var a = {};
while ( a.status !== "finished" ){if ( status === "processing" ){a.status = "finished";}
if ( status === "starting" ){a.status = "processing";}
if ( !a.hasOwnProperties() ){a.status = "starting";}}
// because Object.keys(new Date()).length === 0;// we have to do some additional checkobj // 👈 null and undefined check&& Object.keys(obj).length === 0&& Object.getPrototypeOf(obj) === Object.prototype
但是请注意,这会创建一个不必要的数组(keys的返回值)。
预ECMA 5:
function isEmpty(obj) {for(var prop in obj) {if(Object.prototype.hasOwnProperty.call(obj, prop)) {return false;}}
return JSON.stringify(obj) === JSON.stringify({});}