Traversal Array
can take the subscript loop, traverse Map
and Set
cannot use subscript. In order to unify collection types, the ES6 standard introduces new iterable
types Array
, Map
and Set
all of them belong to iterable
types.
A iterable
collection with a type can traverse through a new for ... of
loop.
varA = [' A ', ' B ', ' C '];vars =NewSet ([' A ', ' B ', ' C ']);varm =NewMap ([[1, ' X '], [2, ' Y '], [3, ' Z ']]); for(varX of a) {//Traversal Arrayalert (x);} for(varX of s) {//traversing setalert (x);} for(varX of M) {//Traverse MapAlert (x[0] + ' = ' + x[1]);}
You may have questions about for ... of
for ... in
What is the difference between loops and loops?
for ... in
The loop is actually a property name of the object that is traversed because of historical problems. An Array
array is actually an object, and its index of each element is treated as an attribute.
When we manually Array
add extra attributes to an object, the for ... in
loop brings unexpected unintended effects:
var a = [' A ', ' B ', ' C '= ' Hello '; for (var in a) { // ' 0 ', ' 1 ', ' 2 ', ' Name '}
for ... in
Loops will be name
included, but Array
the length
attributes are not included.
for ... of
Loops completely fix these problems by looping only the elements of the collection itself:
var a = [' A ', ' B ', ' C '= ' Hello '; for (var X of a) { // ' A ', ' B ', ' C '}
This is why you should introduce a new for ... of
loop.
However, a better approach is to use the built-in iterable
forEach
method directly, which receives a function that automatically callbacks the function each time it iterates. Take Array
for example:
var a = [' A ', ' B ', ' C '];a.foreach ( element, index, array) { // element: A value pointing to the current element // Index: Pointing to the current index // array: Pointing to the Array object itself alert (element);});
Set
Array
similar but Set
no index, so the first two parameters of the callback function are the elements themselves:
var New Set ([' A ', ' B ', ' C ']); S.foreach (function (element, sameelement, set) { alert (Element) ;});
Map
The callback function parameters are sequentially value
, key
and map
themselves:
var New Map ([[1, ' X '], [2, ' Y '], [3, ' Z ']]); M.foreach (function (value, key, map) { alert (value);});
04.javascript--Introduction Some methods record the iterable