search
HomeWeb Front-endFront-end Q&ACan arrays in ES6 be traversed using for of?

Can arrays in ES6 be traversed using for of?

Oct 21, 2022 pm 05:23 PM
javascriptes6es6 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
}
  • 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

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

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

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"

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

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

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

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);
}

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

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

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

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
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
React's SEO-Friendly Nature: Improving Search Engine VisibilityReact's SEO-Friendly Nature: Improving Search Engine VisibilityApr 26, 2025 am 12:27 AM

Yes,ReactapplicationscanbeSEO-friendlywithproperstrategies.1)Useserver-siderendering(SSR)withtoolslikeNext.jstogeneratefullHTMLforindexing.2)Implementstaticsitegeneration(SSG)forcontent-heavysitestopre-renderpagesatbuildtime.3)Ensureuniquetitlesandme

React's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsReact's Performance Bottlenecks: Identifying and Optimizing Slow ComponentsApr 26, 2025 am 12:25 AM

React performance bottlenecks are mainly caused by inefficient rendering, unnecessary re-rendering and calculation of component internal heavy weight. 1) Use ReactDevTools to locate slow components and apply React.memo optimization. 2) Optimize useEffect to ensure that it only runs when necessary. 3) Use useMemo and useCallback for memory processing. 4) Split the large component into small components. 5) For big data lists, use virtual scrolling technology to optimize rendering. Through these methods, the performance of React applications can be significantly improved.

Alternatives to React: Exploring Other JavaScript UI Libraries and FrameworksAlternatives to React: Exploring Other JavaScript UI Libraries and FrameworksApr 26, 2025 am 12:24 AM

Someone might look for alternatives to React because of performance issues, learning curves, or exploring different UI development methods. 1) Vue.js is praised for its ease of integration and mild learning curve, suitable for small and large applications. 2) Angular is developed by Google and is suitable for large applications, with a powerful type system and dependency injection. 3) Svelte provides excellent performance and simplicity by compiling it into efficient JavaScript at build time, but its ecosystem is still growing. When choosing alternatives, they should be determined based on project needs, team experience and project size.

Keys and React's Reconciliation Algorithm: Improving PerformanceKeys and React's Reconciliation Algorithm: Improving PerformanceApr 26, 2025 am 12:21 AM

KeysinReactarespecialattributesassignedtoelementsinarraysforstableidentity,crucialforthereconciliationalgorithmwhichupdatestheDOMefficiently.1)KeyshelpReacttrackchanges,additions,orremovalsinlists.2)Usingunique,stablekeyslikeIDsratherthanindicespreve

The Boilerplate Code Required for React Projects: Reducing Setup OverheadThe Boilerplate Code Required for React Projects: Reducing Setup OverheadApr 26, 2025 am 12:19 AM

ToreducesetupoverheadinReactprojects,usetoolslikeCreateReactApp(CRA),Next.js,Gatsby,orstarterkits,andmaintainamodularstructure.1)CRAsimplifiessetupwithasinglecommand.2)Next.jsandGatsbyoffermorefeaturesbutalearningcurve.3)Starterkitsprovidecomprehensi

Understanding useState(): A Comprehensive Guide to React State ManagementUnderstanding useState(): A Comprehensive Guide to React State ManagementApr 25, 2025 am 12:21 AM

useState()isaReacthookusedtomanagestateinfunctionalcomponents.1)Itinitializesandupdatesstate,2)shouldbecalledatthetoplevelofcomponents,3)canleadto'stalestate'ifnotusedcorrectly,and4)performancecanbeoptimizedusinguseCallbackandproperstateupdates.

What are the advantages of using React?What are the advantages of using React?Apr 25, 2025 am 12:16 AM

Reactispopularduetoitscomponent-basedarchitecture,VirtualDOM,richecosystem,anddeclarativenature.1)Component-basedarchitectureallowsforreusableUIpieces,improvingmodularityandmaintainability.2)TheVirtualDOMenhancesperformancebyefficientlyupdatingtheUI.

Debugging in React: Identifying and Resolving Common IssuesDebugging in React: Identifying and Resolving Common IssuesApr 25, 2025 am 12:09 AM

TodebugReactapplicationseffectively,usethesestrategies:1)AddresspropdrillingwithContextAPIorRedux.2)HandleasynchronousoperationswithuseStateanduseEffect,usingAbortControllertopreventraceconditions.3)OptimizeperformancewithuseMemoanduseCallbacktoavoid

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use