Get object properties (all properties, enumerable, not enumerated, their properties inherited] [Non prototype chain) number Detailed

First, access enumerable property

Method One: for ...... in

Method a: Object.keys ()

Object.keys() The method returns an array of a given object itself may be enumerated attributes of the array and the order of the attribute name used  for...in consistent with the sequence returns when the loop through the object.

grammar

Object.keys(obj)

parameter

obj: to return to their own property enumeration of objects.

return value

A string representing an array of a given object enumeration of all attributes.

example

// simple array
var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo is a property which isn't enumerable
var myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  } 
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

note

In ES5, if this method of argument is not an object (but a raw value), then it throws TypeError. In ES2015, the non-object parameter to be cast to an object.

Object.keys("foo");
// TypeError: "foo" is not an object (ES5 code)

Object.keys("foo");
// ["0", "1", "2"]                   (ES2015 code)

Second, get enumerable and non-enumerable properties

Object.getOwnPropertyNames()Method returns the name of a property of all attributes of the specified object itself (not including but not enumerated attribute as the attribute value name Symbol) consisting of an array, the array order of the attributes enumerated by  for...in circulating (or  Object.keys) of the iteration

The same time as the property. Array defined order attributes can not be enumerated.

If you want to get all the properties of an object ,, not even enumerate, check Object.getOwnPropertyNames.

grammar

Object.getOwnPropertyNames(obj)

parameter

obj:An object itself and not enumerable enumerated attribute name is returned.

return value

String array corresponding to own property found on a given object.

Examples

var arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort()); // ["0", "1", "2", "length"]

// 类数组对象
var obj = { 0: "a", 1: "b", 2: "c"};
console.log(Object.getOwnPropertyNames(obj).sort()); // ["0", "1", "2"] 

use Array.forEach output attribute names and values//
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + " -> " + obj[val]);
});
// 输出
// 0 -> a
// 1 -> b
// 2 -> c

//不可枚举属性
var my_obj = Object.create({}, {
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});
my_obj.foo = 1;

console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]

Third, access to non-enumerable properties

filter()方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。 

Using method (using an array of property names from all the obtaining method) can be removed enumerated attributes (using the method to obtain), the remaining attributes of the property is not enumerable: Array.prototype.filter() Object.getOwnPropertyNames()Object.keys()

var target = the myObject;
 var enum_and_nonenum = Object.getOwnPropertyNames (target);
 var enum_only = Object.keys (target);
 var nonenum_only = enum_and_nonenum.filter (function (Key) {
     var indexInEnum = enum_only.indexOf (Key);
     IF (indexInEnum == - . 1 ) {
         // is not found in healthy enum_only concentration means that the key is not enumerable,
         // thus held so that it returns true filter results in a 
        return  true ; 
    } the else {
         return  to false ; 
    } 
});

console.log(nonenum_only);

prompt

In ES5, if the argument is not a primitive object type, it will throw an  TypeError  exception. In ES2015, the non-object parameter to the object to be cast  .

Object.getOwnPropertyNames('foo');
// TypeError: "foo" is not an object (ES5 code)

Object.getOwnPropertyNames('foo');
// ['length', '0', '1', '2']  (ES2015 code)

Fourth, own property [non-inherited prototype chain]

Use obj.hasOwnProperty () method, Object.prototype.hasOwnProperty () returns a Boolean value indicating whether the attribute of the object itself having the specified properties (i.e., whether a specified key), which will ignore those from the prototype chain on inherited property.

grammar

obj.hasOwnProperty(prop)

parameter

: prop to be detected attribute  String name string represented in the form of, or  Symbol.

return value

Boolean used to determine whether an object has a specified property  Boolean.

Examples

1, using the  hasOwnProperty method for determining whether there is a property

The following example of the detection of an object  o if it contains its own attributes  prop:

o = new Object (); 
o.hasOwnProperty ( ' close ' ); // 返回false 
o.prop = ' exists ' ; 
o.hasOwnProperty ( ' close ' ); // 返回true 
delete o.prop; 
o.hasOwnProperty ( ' close ' ); // 返回false

2, own property and inherit property

The following example illustrates a  hasOwnProperty method to treat the difference between their property and inheritance properties:

o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // 返回 true
o.hasOwnProperty('toString');         // 返回 false
o.hasOwnProperty('hasOwnProperty');   // 返回 false

Remark

Even if the value of the property is  null or  undefined, as long as the property exists, hasOwnProperty still will return  true.

o = new Object();
o.propOne = null;
o.hasOwnProperty('propOne'); // 返回 true
o.propTwo = undefined;  
o.hasOwnProperty('propTwo'); // 返回 true

3, using  hasOwnProperty as an attribute name

JavaScript and did not protect  hasOwnProperty the property name, so when an object may own a property name of the property is occupied, the need to use an external  hasOwnProperty obtain correct results:

var foo = { 
  hasOwnProperty: function () { 
    return  to false ; 
  }, 
  bar: ' Here BE Dragons ' 
}; 

foo.hasOwnProperty ( ' bar ' ); // always returns to false 

// if worried case,
 // directly hasOwnProperty method using real prototype chain 
({}) hasOwnProperty.call (foo,. ' bar ' ); // to true 

// to be used on the property hasOwnProperty Object prototype 
Object.prototype.hasOwnProperty.call (foo, ' bar ' ); // to true

Note that only in the last case, it will not create any new objects.

Remark

Even if the value of the property is  null or  undefined, as long as the property exists, hasOwnProperty still will return  true.

o = new Object();
o.propOne = null;
o.hasOwnProperty('propOne'); // 返回 true
o.propTwo = undefined;  
o.hasOwnProperty('propTwo'); // 返回 true

4, the number of the acquired object property

var AttributeCount = function (obj) {
         var COUNT = 0 ;
         for ( var I in obj) {
             IF (obj.hasOwnProperty (I)) {   // suggested adding judgment, if there is no extended object properties may be used without 
                COUNT ++ ; 
            } 
        } 
        return COUNT; 
    }
alert(attributeCount(testObj));

or 

Cycle, just take own attributes
 var COUNT = 0 ;
 for ( var I in obj) {
     IF (obj.hasOwnProperty (I)) { 
        COUNT ++ 
    } 
} 
the console.log (COUNT);

parameter

MDN:Object.getOwnPropertyNames()

MDN:Object.keys()

MDN:Object.prototype.hasOwnProperty()

 

 

 

Guess you like

Origin www.cnblogs.com/kunmomo/p/12005794.html