This article brings you some commonly used traversal methods for iterable in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In es6, new Map and Set objects are introduced. Array can be traversed through subscripts, but Map and Set cannot be traversed through subscripts. In order to unify collections, es has introduced a new iterable type. Array, Map, and Set types all belong to iterable.
Let’s talk about several commonly used traversal methods.
1.for..in
var a = [1,2,3];for(var index in a ){ console.log(index); console.log(a[index]);}
The above outputs 0,1,2 1,2,3
Only Array can have for..in Both Map and Set It cannot be used, for..in traverses the index
2.for..of
for(var x of a){ console.log(x);}
var d = new Set(['A', 'B', 'C']);for(var dd of d){ console.log(dd);}
for..of traverses the value
This is the result of the above operation.
The difference between for..of and for..in
for..of is a newly introduced concept in es6,
for ... in
Loop Due to historical issues, what it traverses is actually the attribute names of the object. An Array
array is actually an object, and the index of each element is treated as a property.
When we manually add additional attributes to the Array
object, the for ... in
loop will bring unexpected unexpected effects:
var a = ['A', 'B', 'C']; a.name = 'Hello';for (var x in a) { console.log(x); // '0', '1', '2', 'name'
3.foreach() method
var d = new Set(['A', 'B', 'C']);for(var dd of d){ console.log(dd);}
The above is a complete introduction to several commonly used traversal methods of iterable in javascript, if you want to know more aboutJavaScript video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Several commonly used traversal methods for iterable in javascript. For more information, please follow other related articles on the PHP Chinese website!