假设我宣布
var ad = {};
如何检查该对象是否包含用户定义的属性?
假设我宣布
var ad = {};
如何检查该对象是否包含用户定义的属性?
当前回答
我不确定这是否是一个好方法,但我使用这个条件来检查对象是否有或没有任何属性。可以很容易地转化成一个函数。
const obj = {};
if(function(){for (key in obj){return true}return false}())
{
//do something;
}
else
{
//do something else;
}
//Condition could be shorted by e.g. function(){for(key in obj){return 1}return 0}()
其他回答
做一个简单的函数怎么样?
function isEmptyObject(obj) {
for(var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
}
isEmptyObject({}); // true
isEmptyObject({foo:'bar'}); // false
直接在对象上调用hasOwnProperty方法。prototype只是为了增加一点安全性,想象一下下面使用一个普通的obj.hasOwnProperty(…)调用:
isEmptyObject({hasOwnProperty:'boom'}); // false
注:(for future)上述方法依赖于for…在语句中,这个语句只迭代可枚举的属性,在目前最广泛实现的ECMAScript标准(第3版)中,程序员没有任何方法来创建不可枚举的属性。
然而,现在ECMAScript第5版改变了这一点,我们能够创建不可枚举,不可写或不可删除的属性,所以上面的方法可能会失败,例如:
var obj = {};
Object.defineProperty(obj, 'test', { value: 'testVal',
enumerable: false,
writable: true,
configurable: true
});
isEmptyObject(obj); // true, wrong!!
obj.hasOwnProperty('test'); // true, the property exist!!
ECMAScript 5对这个问题的解决方案是:
function isEmptyObject(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
对象。getOwnPropertyNames方法返回一个数组,包含对象的所有属性的名称,可枚举或不可枚举,这个方法现在由浏览器供应商实现,它已经在Chrome 5 Beta和最新的WebKit Nightly Builds中。
Object.defineProperty在这些浏览器和最新的Firefox 3.7 Alpha版本上也可用。
当确定对象是用户定义的对象时,确定UDO是否为空的最简单的方法是以下代码:
isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};
尽管这种方法(本质上)是一种演绎方法,-它是最快的,而且可能是最快的。
a={};
isEmpty(a) >> true
a.b=1
isEmpty(a) >> false
注: 不要在浏览器定义的对象上使用它。
ES6函数
/**
* Returns true if an object is empty.
* @param {*} obj the object to test
* @return {boolean} returns true if object is empty, otherwise returns false
*/
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
例子:
let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false
for (var hasProperties in ad) break;
if (hasProperties)
... // ad has properties
如果你必须确保安全并检查对象原型(这些是由某些库添加的,默认情况下没有):
var hasProperties = false;
for (var x in ad) {
if (ad.hasOwnProperty(x)) {
hasProperties = true;
break;
}
}
if (hasProperties)
... // ad has properties
很晚的回答,但这就是你处理原型的方法。
Array.prototype.Any = function(func) {
return this.some(func || function(x) { return x });
}
Object.prototype.IsAny = function() {
return Object.keys(this).Any();
}