Loop traversal of objects
1. Types of methods
- for in
- Object.keys()
- Object.getOwnPropertyNames()
- Object.OwnPropertySymbols()
- Reflect.ownKeys()
Two, method rules
-
for...in: loop through the object's own and inherited enumerable properties (excluding Symbol properties).
for (const key in obj) { console.log(key + ' --- ' + obj[key]); }
-
Object.keys(obj): returns an array, including all enumerable properties of the object itself (excluding inherited and Symbol properties).
for (const key of Object.keys(obj)) { console.log(key + ' --- ' + obj[key]); }
-
Object.getOwnPropertyNames(obj): returns an array containing all the properties of the object itself (excluding Symbol properties, but including non-enumerable properties).
for (const key of Object.getOwnPropertyNames(obj)) { console.log(key + ' --- ' + obj[key]); }
-
Object.getOwnPropertySymbols(obj): Returns an array containing all Symbol properties of the object itself.
for (const key of Object.getOwnPropertySymbols(obj)) { console.log(key + ' --- ' + obj[key]); }
-
Reflect.ownKeys(obj): returns an array containing all the properties of the object itself (excluding inherited ones).
for (const key of Reflect.ownKeys(obj)) { console.log(key + ' --- ' + obj[key]); }
Three, traverse rules
These methods of traversing the key names of objects all obey the following order rules:
- First traverse all the numeric keys and arrange them in ascending order of numeric value.
- Secondly, all the string keys are traversed and arranged in ascending order according to the time of addition.
- Finally, all Symbol keys are traversed and arranged in ascending order according to the time they were added.