js判斷空對象的方法
判斷一個js對象是不是空對象isEmptyObject
author: @TiffanysBearjavascript
var isEmptyObject = function () {
for (var i in this) {
return false;
}
return true;
}
// 儘可能不要使用object.prototype直接進行修改
// 不然會爲繼承時生成的對象新增沒必要要的可枚舉屬性
// 同時可被for-in枚舉到
Object.defineProperty(Object.prototype, 'isEmptyObject', {
writable: false,
configurable: false,
enumerable: false,
value: isEmptyObject
});
複製代碼
var isEmptyObject = function () {
return JSON.stringify(obj) === '{}';
}
Object.defineProperty(Object.prototype, 'isEmptyObject', {
writable: false,
configurable: false,
enumerable: false,
value: isEmptyObject
});
複製代碼
var isEmptyObject = function () {
return Object.keys(a).length === 0;
}
Object.defineProperty(Object.prototype, 'isEmptyObject', {
writable: false,
configurable: false,
enumerable: false,
value: isEmptyObject
});
複製代碼
若是不支持Object.keys,採用以下的polyfill:java
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
throw new TypeError('Object.keys called on non-object');
}
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
}
})()
};
複製代碼