JavaScript basics: loop traversal of objects

Loop traversal of objects

Insert picture description here

1. Types of methods

  • for in
  • Object.keys()
  • Object.getOwnPropertyNames()
  • Object.OwnPropertySymbols()
  • Reflect.ownKeys()

Two, method rules

  1. 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]);
        }
    
  2. 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]);
        }
    
  3. 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]);
        }
    
  4. 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]);
        }
    
  5. 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:

  1. First traverse all the numeric keys and arrange them in ascending order of numeric value.
  2. Secondly, all the string keys are traversed and arranged in ascending order according to the time of addition.
  3. Finally, all Symbol keys are traversed and arranged in ascending order according to the time they were added.

Guess you like

Origin blog.csdn.net/imagine_tion/article/details/112539538