Home >Web Front-end >Front-end Q&A >Can arrays in ES6 be traversed using for of?
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.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
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.
for (variable of iterable) { statement }
Let’s explore some use cases.
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
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) 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 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
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
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
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
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...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!