JavaScript enumerable and non-enumerable properties

 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:

 

 

 

 

var num = new Number();

for(var pro in num) {

    console.log("num." + pro + " = " + num[pro]);

}

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

function Person() {

    this.name = "KXY";

}

Person.prototype = {

    constructor: Person,

    job: "student",

};

 

var kxy = new Person();

Object.defineProperty(kxy, "sex", {

    value: "female",

    enumerable: false

});

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

for(var pro in kxy) {

    console.log("kxy." + pro + " = " + kxy[pro]);

  }

Traverse results:

Enumeration test 1

You can see that all the attributes except "sex" have been traversed

2.

1

console.log(Object.keys(kxy));

result:

Enumeration test 2

Only the "name" attribute is included, indicating that this method can only return the enumerable attributes of the object itself.

3.

1

console.log(JSON.stringify(kxy));

result:

Enumerability test 3

This method can only read the enumerable properties of the object itself and serialize it into a JSON object.

Guess you like

Origin blog.csdn.net/AN0692/article/details/107511970