js judges whether it can be enumerated

Enumeration refers to whether the properties in the object can be traversed, and to put it simply, whether the properties can be listed.

1. Whether the impact of enumerable properties

for...in traverses its own enumerable properties
Object.keys traverses its own enumerable properties Object.keys traverses its own enumerable properties
JSON.stringify stringify its own enumerable properties

function Person() {
    
    
    this.name = "小明"
};
Person.prototype = {
    
    
    hobby: "打球",
};

var person = new Person();
Object.defineProperty(person, "age", {
    
    
    value: 18,
    enumerable: false
});

// for...in,遍历自身的和原型上继承的可枚举属性
for(var keys in person){
    
    
    console.log(keys);  // name,hobby
}

// Object.keys,遍历自身可枚举属性
console.log(Object.keys(person));  //["name"]

// JSON.stringify,字符串自身可枚举属性
console.log(JSON.stringify(person));    //{"name":"小明"}
  
console.log(Object.assign({
    
    },person));   //{name: "小明"}

2. How to judge whether it is enumerable

Each object has a propertyIsEnumerable() method, this method can determine whether the specified property is enumerable.
Usage: obj.propertyIsEnumerable("property name");

console.log(person.propertyIsEnumerable('name')); //true
console.log(person.propertyIsEnumerable('age'));//false
console.log(person.propertyIsEnumerable('hobby'));//false

3. Summary

The for...in loop is to traverse every enumerable property of the object, including the enumerable properties on the prototype chain;
Object.keys() only traverses its own enumerable properties, not the enumerable properties on the prototype chain. Property, this is the main difference between for...in and Object.keys();
Object.getOwnPropertyNames() traverses all its own properties (whether enumerable or not, excluding those on the prototype chain.

Guess you like

Origin blog.csdn.net/m0_48076809/article/details/109243759
Recommended