Home>Article>Web Front-end> Learn more about for...of loops in JS

Learn more about for...of loops in JS

青灯夜游
青灯夜游 forward
2020-10-12 17:42:44 2667browse

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.

Learn more about for...of loops in JS

#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 theiterablearray.

Map

Mapobject holdskey-valuepairs. Objects and primitive values can be treated as akeyorvalue.MapThe object traverses elements according to the insertion method. In other words,for...ofreturns an array ofkay-valuepairs 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

SetObjects allow you to store unique values of any type, which can be primitive values or objects.SetObject is just a collection of values.SetIteration of elements is based on insertion order, and each value can only occur once. If you create aSetwith 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 theSetwe created has multiple1and2, the traversal output only1and2.

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 theargs()function. So if we pass20arguments to theargs()function, we will output20arguments.

Make some adjustments based on the above example, such as passing in an object, array and function to theargs()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,returnandthrow. 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 thebreakkeyword to terminate a loop and print out only amini.

Ordinary objects are not iterable

for...ofLoops 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 objectobj, when we tryfor...oftoobjWhen 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 alengthproperty 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.

for...ofvs.for...in

for...inIn 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...inNot 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 examplenewArrandanotherNewArrand 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!

Statement:
This article is reproduced at:w3cplus.com. If there is any infringement, please contact admin@php.cn delete