Learn more about for...of loops in JS
This article will give you an in-depth understanding of the for...of loop in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
#The loop created by the for...of statement can traverse objects. The for...of introduced in ES6 can replace the other two loop statements for...in and forEach(), and this new loop statement supports the new iteration protocol. for...of allows you to iterate over iterable data structures, such as arrays, strings, maps, sets, etc.
Syntax
for (variable of iterable) { statement }
variable: The attribute value of each iteration is assigned to the variable
iterable: an object that has enumerable properties and can be iterated
We use some examples to illustrate.
Arrays
Array is a simple list that looks like object. The array prototype has various methods that allow operations to be performed on it, such as traversal. The following example uses for...of to traverse an array:
const iterable = ['mini', 'mani', 'mo']; for (const value of iterable) { console.log(value); } // Output: // => mini // => mani // => mo
The result is to print out each value in the iterable
array.
Map
Map
object holds key-value
pairs. Objects and primitive values can be treated as a key
or value
. Map
The object traverses elements according to the insertion method. In other words, for...of
returns an array of kay-value
pairs on each iteration.
const iterable = new Map([['one', 1], ['two', 2]]); for (const [key, value] of iterable) { console.log(`Key: ${key} and Value: ${value}`); } // Output: // => Key: one and Value: 1 // => Key: two and Value: 2
Set
Set
Objects allow you to store unique values of any type, which can be primitive values or objects. Set
Object is just a collection of values. Set
Iteration of elements is based on insertion order, and each value can only occur once. If you create a Set
with the same element more than once, then it is still considered a single element.
const iterable = new Set([1, 1, 2, 2, 1]); for (const value of iterable) { console.log(value); } // Output: // => 1 // => 2
Although the Set
we created has multiple 1
and 2
, the traversal output only 1
and 2
.
String
String is used to store data in text form.
const iterable = 'javascript'; for (const value of iterable) { console.log(value); } // Output: // => "j" // => "a" // => "v" // => "a" // => "s" // => "c" // => "r" // => "i" // => "p" // => "t"
Here, iterate over the string and print out the characters at (index
) at each index.
Arguments Object
Think of a parameter object as an array-like object corresponding to the parameters passed to the function. Here is a use case:
function args() { for (const arg of arguments) { console.log(arg); } } args('a', 'b', 'c'); // Output: // => a // => b // => c
You may be thinking, what the hell is going on? As I said before, when calling a function, the arguments receive any arguments passed into the args()
function. So if we pass 20
arguments to the args()
function, we will output 20
arguments.
Make some adjustments based on the above example, such as passing in an object, array and function to the args()
function:
function fn(){ return 'functions'; } args('a', 'w3cplus', 'c',{'name': 'airen'},['a',1,3],fn()); // Output: // => "a" // => "w3cplus" // => "c" // => Object { // => "name": "airen" // => } // => Array [ // => "a", // => 1, // => 3 // => ] // => "functions"
Generators
A generator is a function that can exit the function and re-enter the function later.
function* generator(){ yield 1; yield 2; yield 3; }; for (const g of generator()) { console.log(g); } // Output: // => 1 // => 2 // => 3
function* Defines a generator function that returns a generator object. For more information about the generator, you can click here.
Close the iterator
JavaScript provides four known methods to terminate the loop: break
, continue
, return
and throw
. Let’s look at an example:
const iterable = ['mini', 'mani', 'mo']; for (const value of iterable) { console.log(value); break; } // Output: // => mini
In this example, we use the break
keyword to terminate a loop and print out only a mini
.
Ordinary objects are not iterable
for...of
Loops can only work with iteration. But ordinary objects are not iterable. Let's see:
const obj = { fname: 'foo', lname: 'bar' }; for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function console.log(value); }
Here, we define a normal object obj
, when we try for...of
to obj
When operating, an error will be reported: TypeError: obj[Symbol.iterator] is not a function
.
We can convert an array-like object into an array. The object will have a length
property and its elements can be indexed. Let’s look at an example:
const obj = { length: 3, 0: 'foo', 1: 'bar', 2: 'baz' }; const array = Array.from(obj); for (const value of array) { console.log(value); } // Output: // => foo // => bar // => baz
Array.from()
The method creates a new array instance from an array-like (Array-lik) or iterable object.
<span style="font-size: 20px;">for...of</span>
vs. for...in
for...in
In the loop, all enumerable properties in the object will be traversed.
Array.prototype.newArr = () => {}; Array.prototype.anotherNewArr = () => {}; const array = ['foo', 'bar', 'baz']; for (const value in array) { console.log(value); } // Outcome: // => 0 // => 1 // => 2 // => newArr // => anotherNewArr
for...in
Not only can you enumerate the values declared in the array, it can also look for inherited non-enumeration properties from the prototype of the constructor, such as in the above example newArr
and anotherNewArr
and print them out.
for...of
可以对数组和对象等做更具体的操作,但并不表示包括所有对象。
注意:任何具有Symbol.iterator
属性的元素都是可迭代的。
Array.prototype.newArr = function() {}; const array = ['foo', 'bar', 'baz']; for (const value of array) { console.log(value); } // Outcome: // => foo // => bar // => baz
for...of
不考虑构造函数原型的不可枚举属性。它只需要查找可枚举属性并将其打印出来。
总结
理解for...of
循环在开发过程中的用法,可以节省很多时间。希望本文能帮助您理解和编写JavaScript开发中的更好的循环结构。从而让你编码更快乐!
相关免费学习推荐:js视频教程
The above is the detailed content of Learn more about for...of loops in JS. 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

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

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

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

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

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

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
