


Detailed explanation of 5 loop traversal methods of Javascript objects
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!
1. Object traversal method
for ... in
Object.keys(), Object.values(), Object.entries()
##Object.getOwnPropertyNames()
Object.getOwnPropertySymbols()
- ##Reflect.ownKeys()
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
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: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>for (var in object) {
执行的代码块
}</pre><div class="contentsignin">Copy after login</div></div>
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('键名:', i); console.log('键值:', obj[i]); }
Copy after loginOutput 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: 'hello', age: 18 }; console.log(Object.keys(obj)); // 输出结果: ['id', 'name', 'age'] console.log(Object.values(obj)); // 输出结果: [1, 'hello', 18] console.log(Object.entries(obj)); // 输出结果: [['id', 1], ['name', 'hello'], ['age', 18]
Copy after loginNote
- 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()
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 = ['Hello', 'World'];
Object.keys(a) // ["0", "1"]
Object.getOwnPropertyNames(a) // ["0", "1", "length"]
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: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>let obj = {a: 1}
// 给对象添加一个不可枚举的 Symbol 属性
Object.defineProperties(obj, {
[Symbol(&#39;baz&#39;)]: {
value: &#39;Symbol baz&#39;,
enumerable: false
}
})
// 给对象添加一个可枚举的 Symbol 属性
obj[Symbol(&#39;foo&#39;)] = &#39;Symbol foo&#39;
Object.getOwnPropertySymbols(obj).forEach((key) => {
console.log(obj[key])
})
// 输出结果:Symbol baz Symbol foo</pre><div class="contentsignin">Copy after login</div></div>
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, 'method', { 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
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 | NoYes | Contains |
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
