define

In JavaScript, an object’s properties are either enumerable or unenumerable, which are determined by the property’s Enumerable value. Enumerability determines whether this attribute can be used for… In find traversal to.

How do I determine if a property is enumerable

The prototype properties of basic wrapper types in js are not enumerable, such as Object, Array, Number, etc., if you write code to iterate over the properties:


var num = new Number();
for(var pro in num) {
  console.log("num." + pro + "=" + num[pro]);
}

Copy the code

Its output will be null. This is because the built-in attributes in Number are not enumerable and therefore cannot be used by for… In access to.

The propertyIsEnumerable() method of an Object determines whether the Object contains a property and whether it is enumerable.

Note that if the judged property exists in the prototype of an Object, it returns false regardless of whether it is enumerable.

var person = {
    name:'xiao',
    age: '18',
}
 
Object.defineProperty(person,'age',{
    enumerable:true,// can be enumerated}); Object.defineProperty(person,'sex',{
    enumerable:false, / / no can be enumerated}) person. PropertyIsEnumerable ('sex'); //false
person.propertyIsEnumerable('age'); //true
Copy the code

Gets the enumerable properties of the object itself

  • for… In // traverses only enumerable properties on the object itself and the stereotype
  • Object.keys() // Returns the key names of all the enumerable properties of the Object itself

for… In gets enumerable properties

function Test(name){
        this.name=name
    }

    let test=new Test()

    Test.prototype.newF=function(){console.log(this.name)}for(let key in test){console.log(key) //name, newF gets enumerable properties on its own and prototypefor(let key in test) {if(test.hasOwnProperty(key)){
            console.log(key) //name 
        }
    }
Copy the code

Object.key() gets an enumerable property

let keyArr=Object.key(test) / / /'name'] You can see from the output that only the enumerable properties of the object declaration are printed, but not the enumerable properties in the stereotype chainCopy the code