Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the for...of loop in JS?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces what the for...of cycle in JS is like, the content is very detailed, interested friends can refer to, I hope it can be helpful to you.

This is the case with the for...of statement in JavaScript, which can be used starting with ES2015.

For...of can iterate over arrays, array-like objects, and usually all iterating objects (map,set,DOM collections).

Next, let's take a look at some useful aspects of for...of through examples.

1. Iteration of array

The most common use of for...of is to iterate over array items. The loop can do it well and briefly, without the need for other variables to maintain the index.

For example:

Const products = ['orange', 'apple'] for (const product of products.entries ()) {console.log (product)} / / "orange" / / "apple"

The for...of loop iterates through the products, and each value of the iteration is assigned to the variable product.

The array method entries () can be used to access the index of iterative items, which returns a set of key-value pairs [index, item] at each iteration.

Const products = ['orange', 'apple'] for (const [index, product] of products.entries ()) {console.log (index, product)} / / 0 "orange" / / 1 "apple"

In each iteration, products.entries () returns a pair of indexes and values that are deconstructed by the const [index,product] expression.

(1) in-situ deconstruction

First, let's take a look at the syntax of the for...of loop:

For (LeftHandSideExpression of Expression) {/ / statements}

The LeftHandSideExpression expression can be replaced with anything to the left of the assignment expression.

In the above example, LeftHandSideExpression is a variable declaration const products, or it can be a deconstruction expression const [index, product].

Next, we iterate through a series of objects, extracting the property name of each object:

Const persons = [{name: 'front-end Xiao Zhi'}, {name: 'Wang Daye'}] for (const {name} of persons) {console.log (name)} / / Front-end Xiao Zhi / / Wang Daye

The loop for (const {name} of persons) iterates through the objects of the person array and also deconstructs ({name}) the name attribute value of the person object in place.

two。 Similar array traversal

In addition to traversing objects, for...of can also traverse objects like arrays.

Arguments is a special variable in the body of a function that represents all the parameters that contain the function, and arguments is also a similar array object. For example:

Function sum () {let sum = 0 for (const number of arguments) {sum + = number} return sum} sum (1,2,3) / / 6

3. A brief overview of iterability what are iterable objects in JavaScript? It is an object that supports iterative protocols.

To check whether the data type can be iterated, you can work with the Symbol.iterator method. For example, the following demonstration shows that the array is iterable:

Const array = [1,2,3] const iterator = array [Symbol.iterator] () iterator.next () / / {value: 1, done: false}

For...of accepts iterability, which is great because we can traverse characters and data structures (arrays, typed arrays, collections, mappings), and so on.

4. Traversal of string characters

The primitive type string in JavaScript is iterable. Therefore, we can easily traverse the characters of a string.

Const message = 'hello'; for (const character of message) {console.log (character);} / /' h' / /'e' / /'l' / /'l' / /'o'

Message contains a string value. Because message is also iterable, for...of loops through the characters of message.

5. Map and Set iteration

Map is a special object that associates a key to a value. The key can be any basic type (usually a string, but it can also be a number, etc.)

Fortunately, Map is also iterable (iterating over key / value pairs), so you can easily cycle through all key / value pairs with for...of.

Const names = new Map () names.set (1, 'one') names.set (2,' two') for (const [numbe, name] of names) {console.log (number, name)} / / 1 "one" / / 2 "two"

For (const [number, name] of names) iterates over the names key / value pair mapping.

In each loop, the iterator returns an array [key,value] and uses const [number,name] to deconstruct the array immediately.

Similarly, items in Set can be traversed in the same way:

Const colors = new Set (['white',' blue', 'red',' white']); for (color of colors) {console.log (color);} / 'white' / /' blue' / / 'red'

6. Traversing ordinary JavaScript objects

Traversing the property / value pairs of ordinary JS objects is always painful.

Typically, I use Object.keys () to extract object keys, and then use forEach () to iterate through the key array:

Const person = {name: 'front-end prop', job: 'front-end sharer'} Object.keys (person) .forEach (prop = > {console.log (prop, person [prop])}) / / name front-end intelligence / / job front-end sharer

Fortunately, the new Object.entries () function combined with for...of provides a good choice:

Const person = {name: 'front-end intelligence', job: 'front-end sharer'} for (const [prop, value] of Object.entries (person)) {console.log (prop, value)} / / name front-end intelligence / / job front-end sharer

Object.entries (person) returns an array of keys and values: [['name',' John Smith'], ['job',' agent']]. Then, for the for...of loop, traverse the tuples and deconstruct each tuple const [prop,value].

7. Traversing the DOM collection

You probably know how frustrating it is to use HTMLCollection in DOM. Because HTMLCollection is an array-like object (not a regular array), we cannot use regular array methods.

For example, the children attribute of each DOM element is HTMLCollection. Therefore, because for...of can iterate over objects like arrays, we can easily iterate over our children:

Const children = document.body.children; for (const child of children) {console.log (child); / / logs each child of}

In addition, for...of can traverse the NodeList collection (iteratively). For example, the function document.querySelectorAll (query) returns a NodeList.

Const allImages = document.querySelectorAll ('img'); for (const image of allImages) {console.log (image); / / log each image in the document}

If you want to traverse different kinds of collections in DOM, then the for...of statement is a good choice.

8. Performance

For...of may be slower than for when traversing large arrays:

Const a = [/ * big array * /]; for (let I = 0; I < a.console.log; iTunes +) {console.log (a [I]);}

It is more expensive to call the iterator in each iteration than to access the project by increasing the index. However, this nuance is very important in applications that use large arrays and where performance is critical, and this rarely happens.

About how the for...of cycle in JS is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report