In JavaScript, the properties of an object are divided into enumerable and non-enumerable, and they are determined by the enumerable value of the property. Enumerability determines whether this attribute can be traversed by for...in search.
1. How to judge whether the attribute is enumerable
The prototype properties of the basic packaging types in js are not enumerable, such as Object, Array, Number, etc. If you write such code to traverse the properties:
|
|
Its output will be empty. This is because the built-in properties in Number are not enumerable, so they cannot be accessed by for...in.
The propertyIsEnumerable() method of the Object object can determine whether this object contains a certain property, and whether this property is enumerable.
It should be noted that if the judged property exists in the prototype of the Object object, it will return false regardless of whether it is enumerable or not.
Second, the role of enumeration
The enumeration of attributes affects the results of the following three functions:
for…in
Object.keys()
JSON.stringify
First look at an example, create a kxy object as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Among them, defineProperty is used to define a non-enumerable property named "sex" for the object
Next, do the following verification:
1.
1 2 3 |
|
Traverse results:
You can see that all the attributes except "sex" have been traversed
2.
1 |
|
result:
Only the "name" attribute is included, indicating that this method can only return the enumerable attributes of the object itself.
3.
1 |
|
result:
This method can only read the enumerable properties of the object itself and serialize it into a JSON object.