Table of Contents
What is a for...of loop
Syntax
Use Cases
Arrays(array)
Maps(mapping)
Set(set)
String(String)
Arguments Object(parameter object)
Generators
Exit iteration
Normal objects are not iterable
For…of vs For…in
小结
Home Web Front-end Front-end Q&A Can arrays in ES6 be traversed using for of?

Can arrays in ES6 be traversed using for of?

Oct 21, 2022 pm 05:23 PM
javascript es6 es6 array

Arrays in es6 can be traversed using for of. The "for...of" statement creates a loop to iterate iterable objects. ES6 introduces the "for...of" loop to replace "for...in" and forEach() and supports the new iteration protocol. ; The "for...of" statement allows developers to traverse iterable data structures such as Arrays, Strings, Maps, and Sets.

Can arrays in ES6 be traversed using for of?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

What is a for...of loop

The for...of statement creates a loop to iterate over an iterable object. The for...of loop was introduced in ES6 to replace for...in and forEach() and supports the new iteration protocol. for...of Allows you to traverse iterable data structures such as Arrays, Strings, Maps, Sets, etc.

Syntax

for (variable of iterable) {
    statement
}
Copy after login
  • variable: The attribute value of each iteration is assigned to this variable.
  • iterable: An object that has enumerable properties and can be iterated.

Use Cases

Let’s explore some use cases.

Arrays(array)

Arrays(array) is a list-like object. There are various methods on the array prototype that allow operations on it, such as modification and traversal. The following for...of operation performed on an array:

// array-example.js
const iterable = ['mini', 'mani', 'mo'];
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// mini
// mani
// mo
Copy after login

The result is to print out each value in the iterable array.

Demo: https://jsbin.com/dimahag/edit?js,console

Maps(mapping)

Map object is to save key-value(key value) right. Objects and primitive values ​​can be used as keys or values. Map object iterates elements based on how they were inserted. In other words, the for...of loop will return a key-value array for each iteration.

// map-example.js
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
Copy after login

Demo: https://jsbin.com/lofewiw/edit?js,console

Set(set)

Set(set) object allows you to store any type Unique values ​​that can be primitive values ​​or objects. A Set object is simply a collection of values. Iteration of Set elements is based on their insertion order. A value in a Set can only occur once. If you create a Set with multiple identical elements, it is still considered a single element.

// set-example.js
const iterable = new Set([1, 1, 2, 2, 1]);
 
for (const value of iterable) {
  console.log(value);
}
// Output:
// 1
// 2
Copy after login

Although our Set has multiple 1 and 2, the output is only 1 and 2.

Demo: https://jsbin.com/fajozob/edit?js,console

String(String)

String is used to store data in text form.

// string-example.js
const iterable = 'javascript';
 
for (const value of iterable) {
  console.log(value);
}
 
// Output:
// "j"
// "a"
// "v"
// "a"
// "s"
// "c"
// "r"
// "i"
// "p"
// "t"
Copy after login

Here, iterate over the string and print out the characters at each index.

Demo: https://jsbin.com/rixakeg/edit?js,console

Arguments Object(parameter object)

Consider a parameter object as a class An array-like object and corresponds to the arguments passed to the function. Here is a use case:

// arguments-example.js
function args() {
  for (const arg of arguments) {
    console.log(arg);
  }
}
 
args('a', 'b', 'c');
// Output:
// a
// b
// c
Copy after login

You may be thinking, what happened?! As mentioned before, when calling a function, arguments will receive the incoming args() Any parameters of the function. So, if we pass 20 arguments to the args() function, we will print out 20 arguments.

Demo: https://jsbin.com/ciqabov/edit?js,console

Generators

A generator is a function that can exit the function , and re-enter the function later.

// generator-example.js
function* generator(){ 
  yield 1; 
  yield 2; 
  yield 3; 
}; 
 
for (const g of generator()) { 
  console.log(g); 
}
 
// Output:
// 1
// 2
// 3
Copy after login

function* defines a generator function that returns a generator object. For more information about the generator, click here.

Demo: https://jsbin.com/faviyi/edit?js,console

Exit iteration

JavaScript provides four known methods for terminating loop execution : 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
Copy after login

In this example, we use the break keyword to terminate the loop after one execution, so only mini is printed.

Demo: https://jsbin.com/tisuken/edit?js,console

Normal objects are not iterable

for...of Loops only work with iteration. And ordinary objects are not iterable. Let's take a look:

const obj = { fname: 'foo', lname: 'bar' };
 
for (const value of obj) { // TypeError: obj[Symbol.iterator] is not a function
    console.log(value);
}
Copy after login

Here, we define a normal object obj , and when we try for...of to operate on it, An error will be reported: TypeError: obj[Symbol.iterator] is not a function.

Demo: https://jsbin.com/sotidu/edit?js,console

我们可以通过将类数组(array-like)对象转换为数组来绕过它。该对象将具有一个 length 属性,其元素必须可以被索引。我们来看一个例子:

// object-example.js
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
Copy after login

Array.from() 方法可以让我通过类数组(array-like)或可迭代对象来创建一个新的 Array(数组) 实例。

Demo: https://jsbin.com/miwofin/edit?js,console

For…of vs For…in

for...in 循环将遍历对象的所有可枚举属性。

//for-in-example.js
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
Copy after login

for...in 不仅枚举上面的数组声明,它还从构造函数的原型中查找继承的非枚举属性,在这个例子中,newArr 和 anotherNewArr 也会打印出来。

Demo: https://jsbin.com/quxojof/edit?js,console

for...of 更多用于特定于集合(如数组和对象),但不包括所有对象。

注意:任何具有 Symbol.iterator 属性的元素都是可迭代的。

Array.prototype.newArr = () => {};
const array = ['foo', 'bar', 'baz'];
 
for (const value of array) { 
  console.log(value);
}
// Outcome:
// foo
// bar
// baz
Copy after login

for...in 不考虑构造函数原型的不可枚举属性。它只需要查找可枚举属性并将其打印出来。

Demo: https://jsbin.com/sakado/edit?js,console

小结

了解 for...of 循环的使用可以在开发过程中节省大量的时间。 希望本文帮助你在JavaScript开发中了解和编写更好的循环结构。 让你快乐编码!

完整的示例代码:https://github.com/codediger/javascript-for-of-loop

【相关推荐:javascript视频教程编程视频

The above is the detailed content of Can arrays in ES6 be traversed using for of?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

See all articles