如何检查对象在 JavaScript 中是否有任何属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2673121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if object has any properties in JavaScript?
提问by Ricky
Assuming I declare
假设我声明
var ad = {};
How can I check whether this object will contain any user-defined properties?
如何检查此对象是否包含任何用户定义的属性?
采纳答案by Daniel Vassallo
You can loop over the properties of your object as follows:
您可以循环遍历对象的属性,如下所示:
for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
It is important to use the hasOwnProperty()method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.
使用hasOwnProperty()方法很重要,以确定对象是否具有作为直接属性的指定属性,而不是从对象的原型链继承。
Edit
编辑
From the comments:You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment
来自评论:您可以将该代码放在一个函数中,并在到达有评论的部分后立即返回 false
Performance Test
性能测试
Test Of Object.Keys vs For..In When testing for any properties
回答by Dhaval Chaudhary
You can use the built in Object.keysmethod to get a list of keys on an object and test its length.
您可以使用内置Object.keys方法获取对象上的键列表并测试其长度。
var x = {};
// some code where value of x changes and than you want to check whether it is null or some object with values
if(Object.keys(x).length > 0){
// Your code here if x has some properties
}
回答by CMS
What about making a simple function?
做一个简单的函数怎么样?
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
The hasOwnPropertymethod call directly on the Object.prototypeis only to add little more safety, imagine the following using a normal obj.hasOwnProperty(...)call:
该hasOwnProperty方法调用直接上Object.prototype只加一点更安全,试想使用正常以下obj.hasOwnProperty(...)电话:
isEmptyObject({hasOwnProperty:'boom'}); // false
Note:(for the future)The above method relies on the for...instatement, and this statement iterates only over enumerableproperties, in the currently most widely implemented ECMAScript Standard (3rd edition) the programmer doesn't have any way to create non-enumerable properties.
注意:(为了以后)上面的方法依赖于for...in语句,并且这个语句只迭代可枚举属性,在目前最广泛实现的ECMAScript Standard(第3版)中程序员没有任何方法可以创建不可枚举的属性.
However this has changed now with ECMAScript 5th Edition, and we are able to create non-enumerable, non-writable or non-deletable properties, so the above method can fail, e.g.:
然而,现在ECMAScript 5th Edition改变了这一点,我们能够创建不可枚举、不可写或不可删除的属性,因此上述方法可能会失败,例如:
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!!
An ECMAScript 5 solution to this problem would be:
这个问题的 ECMAScript 5 解决方案是:
function isEmptyObject(obj) {
return Object.getOwnPropertyNames(obj).length === 0;
}
The Object.getOwnPropertyNamesmethod returns an Arraycontaining the names of allthe own propertiesof an object, enumerable or not, this method is being implemented now by browser vendors, it's already on the Chrome 5 Beta and the latest WebKit Nightly Builds.
该Object.getOwnPropertyNames方法返回一个Array包含的名字都在自己的属性的对象,而枚举与否,现在正在实施的浏览器厂商这种方法,它已经在Chrome 5 Beta版和最新的WebKit的每晚构建。
Object.definePropertyis also available on those browsers and latest Firefox 3.7 Alpha releases.
Object.defineProperty也可在这些浏览器和最新的 Firefox 3.7 Alpha 版本上使用。
回答by kayz1
With jQueryyou can use:
使用jQuery,您可以使用:
$.isEmptyObject(obj); // Returns: Boolean
As of jQuery 1.4 this method checks both properties on the object itself and properties inherited from prototypes (in that it doesn't use hasOwnProperty).
从 jQuery 1.4 开始,此方法检查对象本身的属性和从原型继承的属性(因为它不使用 hasOwnProperty)。
With ECMAScript 5th Editionin modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keysmethod:
随着ECMAScript的第5版的现代浏览器(IE9 +,FF4 +,Chrome5 +,Opera12 +,Safari5 +),你可以使用内置的Object.keys方法:
var obj = { blah: 1 };
var isEmpty = !Object.keys(obj).length;
Or plain old JavaScript:
或者普通的旧 JavaScript:
var isEmpty = function(obj) {
for(var p in obj){
return false;
}
return true;
};
回答by Zaptree
Most recent browsers (and node.js) support Object.keys() which returns an array with all the keys in your object literal so you could do the following:
最近的浏览器(和 node.js)支持 Object.keys() ,它返回一个数组,其中包含对象文字中的所有键,因此您可以执行以下操作:
var ad = {};
Object.keys(ad).length;//this will be 0 in this case
Browser Support: Firefox 4, Chrome 5, Internet Explorer 9, Opera 12, Safari 5
浏览器支持:Firefox 4、Chrome 5、Internet Explorer 9、Opera 12、Safari 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
回答by Gruff Bunny
回答by sfs
回答by Casey Chu
for (var hasProperties in ad) break;
if (hasProperties)
... // ad has properties
If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):
如果您必须确保安全并检查对象原型(这些是由某些库添加的,默认情况下不存在):
var hasProperties = false;
for (var x in ad) {
if (ad.hasOwnProperty(x)) {
hasProperties = true;
break;
}
}
if (hasProperties)
... // ad has properties
回答by Warty
for(var memberName in ad)
{
//Member Name: memberName
//Member Value: ad[memberName]
}
Member means Member property, member variable, whatever you want to call it >_>
Member的意思是Member属性,成员变量,随便你叫什么>_>
The above code will return EVERYTHING, including toString... If you only want to see if the object's prototype has been extended:
上面的代码会返回所有的东西,包括 toString... 如果你只想查看对象的原型是否已经扩展:
var dummyObj = {};
for(var memberName in ad)
{
if(typeof(dummyObj[memberName]) == typeof(ad[memberName])) continue; //note A
//Member Name: memberName
//Member Value: ad[memberName]
}
Note A: We check to see if the dummy object's member has the same type as our testing object's member. If it is an extend, dummyobject's member type should be "undefined"
注意 A:我们检查虚拟对象的成员是否与我们的测试对象的成员具有相同的类型。如果是extend,dummyobject的成员类型应该是“undefined”
回答by Jimbo Jonny
var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
// as of this line hasAnyProps will show Boolean whether or not any iterable props exist
Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOTloop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)
操作简单,工作在每一个浏览器,即使它在技术上的对象上的所有键它的循环不循环通过他们... ...无论有0和循环不运行或有一些它的第一爆发后一个(因为我们正在检查的只是是否有任何......那么为什么要继续?)

