Home >Web Front-end >JS Tutorial >Detailed explanation of 5 loop traversal methods of Javascript objects

Detailed explanation of 5 loop traversal methods of Javascript objects

青灯夜游
青灯夜游Original
2022-08-04 17:28:2735704browse

How to loop through Javascript objects? The following article will introduce five JS object traversal methods in detail, and briefly compare these five methods. I hope it will be helpful to you!

Detailed explanation of 5 loop traversal methods of Javascript objects

1. Object traversal method

  • for ... in

  • Object.keys(), Object.values(), Object.entries()

  • ##Object.getOwnPropertyNames()

  • Object.getOwnPropertySymbols()

  • ##Reflect.ownKeys()

  • 2. Object attribute traversal order rules

The above five methods all

obey the same attribute traversal order rules when traversing the properties of an object

    The attribute name is
  • value

    , sorted in ascending order by value

  • The attribute name is
  • String

    , sorted in ascending order by generation time

  • The attribute name is
  • Symbol

    , sorted in ascending order by generation time

3. Detailed explanation of traversal method

1. for in

for…in

Mainly used for looping object properties. Each time the code in the loop is executed, the properties of the object will be operated on. The syntax is as follows: <pre class="has">for (var in object) { 执行的代码块 }</pre>Two parameters:

    var: required. The specified variable can be an array element or an object property.
  • object: required. Specifies the object to iterate over.
  • var obj = {a: 1, b: 2, c: 3}; 
     
    for (var i in obj) { 
        console.log(&#39;键名:&#39;, i); 
        console.log(&#39;键值:&#39;, obj[i]); 
    }
  • Output result:
键名:a
键值:1
键名:b
键值:2
键名:c
键值:3

Note:

    The for in method will not only traverse all the enumerable objects of the current object When a property is lifted, the properties on its prototype chain will also be traversed.

2. Object.keys(), Object.values(), Object.entries()This All three methods are used to traverse the object. It will return an array consisting of the given object's own enumerable properties (excluding inherited and Symbol properties). The order of the array elements is the same as that returned when the normal loop traverses the object. In the same order, the values ​​returned by these three elements are as follows:

    Object.keys(): Returns an array containing the object key name;
  • Object.values(): Returns an array containing object key values;
  • Object.entries(): Returns an array containing object key names and key values.
  • let obj = { 
      id: 1, 
      name: &#39;hello&#39;, 
      age: 18 
    };
    console.log(Object.keys(obj));   // 输出结果: [&#39;id&#39;, &#39;name&#39;, &#39;age&#39;]
    console.log(Object.values(obj)); // 输出结果: [1, &#39;hello&#39;, 18]
    console.log(Object.entries(obj));   // 输出结果: [[&#39;id&#39;, 1], [&#39;name&#39;, &#39;hello&#39;], [&#39;age&#39;, 18]
  • Note

    The values ​​in the array returned by the Object.keys() method are all strings, which means they are not strings The key value will be converted into a string.
  • The attribute values ​​in the result array are all
  • enumerable attributes

    of the object itself, excluding inherited attributes.

  • 3. Object.getOwnPropertyNames()

Object.getOwnPropertyNames()

The method is similar to Object.keys() , also accepts an object as a parameter and returns an array containing all the property names of the object itself. But it can return non-enumerable properties.

let a = [&#39;Hello&#39;, &#39;World&#39;];
 
Object.keys(a) // ["0", "1"]
Object.getOwnPropertyNames(a) // ["0", "1", "length"]
Both methods can be used to count the number of properties in an object:

var obj = { 0: "a", 1: "b", 2: "c"};
Object.getOwnPropertyNames(obj) // ["0", "1", "2"]
Object.keys(obj).length // 3
Object.getOwnPropertyNames(obj).length // 3

4. Object.getOwnPropertySymbols()

Object.getOwnPropertySymbols()

The method returns an array of Symbol properties of the object itself, excluding string properties: <pre class="has">let obj = {a: 1} // 给对象添加一个不可枚举的 Symbol 属性 Object.defineProperties(obj, { [Symbol(&amp;#39;baz&amp;#39;)]: { value: &amp;#39;Symbol baz&amp;#39;, enumerable: false } }) // 给对象添加一个可枚举的 Symbol 属性 obj[Symbol(&amp;#39;foo&amp;#39;)] = &amp;#39;Symbol foo&amp;#39; Object.getOwnPropertySymbols(obj).forEach((key) =&gt; { console.log(obj[key]) }) // 输出结果:Symbol baz Symbol foo</pre>

5 . Reflect.ownKeys()Reflect.ownKeys() Returns an array containing all the properties of the object itself. It is similar to Object.keys(). Object.keys() returns property keys, but does not include non-enumerable properties, while Reflect.ownKeys() returns all property keys:

var obj = {
 a: 1,
 b: 2
}
Object.defineProperty(obj, &#39;method&#39;, {
 value: function () {
     alert("Non enumerable property")
 },
 enumerable: false
})
 
console.log(Object.keys(obj))
// ["a", "b"]
console.log(Reflect.ownKeys(obj))
// ["a", "b", "method"]

Note:

    Object.keys(): Equivalent to returning an array of object properties;
  • Reflect.ownKeys(): Equivalent to
  • Object.getOwnPropertyNames( obj).concat(Object.getOwnPropertySymbols(obj)

    .

  • 4. Comparison of traversal methods

Traversal methodsfor ... inObject.keys()Object.getOwnPropertyNames()Object.getOwnPropertySymbols()Reflect.ownKeys()NoYesContains[Related recommendations: javascript learning tutorial
Self properties Inherited properties Traverse basic properties Traverse prototype chain Traverse non-enumerable properties Symbol type
self inherit is Yes No Does not contain
self
Yes
No No Does not contain
Self
Yes
No Yes Does not contain
self
No
No Yes All Symbol properties
self ## is

]

The above is the detailed content of Detailed explanation of 5 loop traversal methods of Javascript objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn