简体   繁体   English

如何检查object是否在JavaScript中有任何属性?

[英]How to check if object has any properties in JavaScript?

Assuming I declare假设我声明

var ad = {}; 

How can I check whether this object will contain any user-defined properties?我如何检查这个 object 是否包含任何用户定义的属性?

You can use the built in Object.keys method 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){
 // Your code here if x has some properties  
}

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 hasOwnProperty method call directly on the Object.prototype is only to add little more safety , imagine the following using a normal obj.hasOwnProperty(...) call:直接在Object.prototype上调用hasOwnProperty方法只是为了增加一点安全性,想象以下使用正常的obj.hasOwnProperty(...)调用:

isEmptyObject({hasOwnProperty:'boom'});  // false

Note: (for the future) The above method relies on the for...in statement, and this statement iterates only over enumerable properties, 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 标准(第 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 , eg:然而,现在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.getOwnPropertyNames method returns an Array containing the names of all the own properties of 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 Nightly Builds 上。

Object.defineProperty is also available on those browsers and latest Firefox 3.7 Alpha releases. Object.defineProperty也可用于这些浏览器和最新的 Firefox 3.7 Alpha 版本。

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

With jQuery you 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 Edition in modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:在现代浏览器(IE9+、FF4+、Chrome5+、Opera12+、Safari5+)中使用ECMAScript 5th Edition ,您可以使用内置的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;
            };

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

If you're using underscore.js then you can use the _.isEmpty function:如果你使用 underscore.js 那么你可以使用_.isEmpty函数:

var obj = {};
var emptyObject = _.isEmpty(obj);

If you are willing to use lodash , you can use the some method.如果你愿意使用lodash ,你可以使用some方法。

_.some(obj) // returns true or false

See this small jsbin example看这个小的jsbin例子

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
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.注意 A:我们检查虚拟对象的成员是否与我们的测试对象的成员具有相同的类型。 If it is an extend, dummyobject's member type should be "undefined"如果是extend,dummyobject的成员类型应该是“undefined”

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 NOT loop 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和循环不运行或有一些它的第一爆发后一个(因为我们正在检查的只是是否有任何......那么为什么要继续?)

ES6 function 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

Examples:例子:


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

Very late answer, but this is how you could handle it with prototypes.答案很晚,但这就是您可以使用原型处理它的方式。

Array.prototype.Any = function(func) {
    return this.some(func || function(x) { return x });
}

Object.prototype.IsAny = function() {
    return Object.keys(this).Any();
}

Late answer, but some frameworks handle objects as enumerables.迟到的答案,但一些框架将对象作为可枚举处理。 Therefore, bob.js can do it like this:因此, bob.js可以这样做:

var objToTest = {};
var propertyCount = bob.collections.extend(objToTest).count();

You can use the following:您可以使用以下内容:

Double bang !!双爆!! property lookup属性查找

var a = !![]; // true
var a = !!null; // false

hasOwnProperty This is something that I used to use: hasOwnProperty这是我曾经使用过的东西:

var myObject = {
  name: 'John',
  address: null
};
if (myObject.hasOwnProperty('address')) { // true
  // do something if it exists.
}

However, JavaScript decided not to protect the method's name, so it could be tampered with.但是,JavaScript 决定不保护方法的名称,因此它可能会被篡改。

var myObject = {
  hasOwnProperty: 'I will populate it myself!'
};

prop in myObject myObject 中的道具

var myObject = {
  name: 'John',
  address: null,
  developer: false
};
'developer' in myObject; // true, remember it's looking for exists, not value.

typeof类型

if (typeof myObject.name !== 'undefined') {
  // do something
}

However, it doesn't check for null.但是,它不检查 null。

I think this is the best way.我认为这是最好的方法。

in operator在运营商

var myObject = {
  name: 'John',
  address: null
};

if('name' in myObject) {
  console.log("Name exists in myObject");
}else{
  console.log("Name does not exist in myObject");
}

result:结果:

Name exists in myObject名称存在于 myObject 中

Here is a link that goes into more detail on the in operator: Determining if an object property exists这是一个更详细地介绍 in 运算符的链接: 确定对象属性是否存在

Object.hasOwn is a new static method (not fully supported by all browsers yet) which checks if the specified object has the indicated property as his own property and return true if that is the case. Object.hasOwn是一个新的 static 方法(尚未被所有浏览器完全支持),它检查指定的 object 是否具有指示的属性作为他自己的属性,如果是,则返回 true。 It will return false if the property is either inherited or does not exist on that object.如果该属性是继承的或不存在于该 object 上,它将返回 false。

You can iterate through the object properties and check if they are indeed own properties您可以遍历 object 属性并检查它们是否确实是自己的属性

for (let property in ad) {
   if (Object.hasOwn(ad, property)) {
    // handle your code for object own properties here
  }
}   

More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/更多关于Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/

Browser compatibility here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility此处的浏览器兼容性 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

I'm not sure if this is a good approach but I use this condition to check if an object has or hasn't any property.我不确定这是否是一个好方法,但我使用此条件来检查 object 是否具有任何属性。 Could be easily transformed into a function.可以轻松转换为 function。

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}()

When sure that the object is a user-defined one, the easiest way to determine if UDO is empty, would be the following code:当确定对象是用户定义的对象时,确定 UDO 是否为空的最简单方法是以下代码:

isEmpty=
/*b.b Troy III p.a.e*/
function(x,p){for(p in x)return!1;return!0};

Even though this method is (by nature) a deductive one, - it's the quickest, and fastest possible.尽管这种方法(本质上)是一种演绎方法,但它是最快的,也是最快的。

a={};
isEmpty(a) >> true

a.b=1
isEmpty(a) >> false 

ps: !don't use it on browser-defined objects. ps:不要在浏览器定义的对象上使用它。

How about this?这个怎么样?

var obj = {},
var isEmpty = !obj;
var hasContent = !!obj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM