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: <pre class='brush:php;toolbar:false;'>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('键名:', i); console.log('键值:', 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: '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]
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()
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"]
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='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>
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!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


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

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment