You can use subscript loops when traversing Array, and you cannot use subscripts when traversing Map and Set. In order to unify the collection types, the ES6 standard introduced new iterable types, and Array, Map and Set are all of iterable types.
haveiterable
Collections of types can be passed through newfor ... of
Loop to traverse.
for ... of
Looping is a new syntax introduced by ES6. Please test whether your browser supports it:
'use strict'; var a = [1, 2, 3]; for (var x of a) { } alert('Your browser supports for... of');
usefor ... of
Looping through the collection, the usage is as follows:
var a = ['A', 'B', 'C']; var s = new Set(['A', 'B', 'C']); var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]); for (var x of a) { // traversal Array alert(x); } for (var x of s) { // traversal Set alert(x); } for (var x of m) { // traverse the map alert(x[0] + '=' + x[1]); }
You may have questions, what is the difference between a for ... of loop and a for ... in loop?
for ... in
Due to historical problems, the loop traverses the property name of the object. oneArray
An array is actually an object, and the index of each element of it is treated as an attribute.
When we manually add extra properties to the Array object, the for ... in loop will bring unexpected unexpected effects:
var a = ['A', 'B', 'C']; = 'Hello'; for (var x in a) { alert(x); // '0', '1', '2', 'name' } for ... inThe loop willnameIncluded,butArrayoflength属性却不Included。 for ... ofLoops completely fix these problems,它只循环集合本身of元素: var a = ['A', 'B', 'C']; = 'Hello'; for (var x of a) { alert(x); // 'A', 'B', 'C' }
That's why new ones are introducedfor ... of
cycle.
However, a better way is to use iterable's built-in forEach method directly, which receives a function that automatically calls back each iteration. Take Array as an example:
var a = ['A', 'B', 'C']; (function (element, index, array) { // element: Point to the value of the current element // index: Point to the current index // array: Point to the Array object itself alert(element); });
Notice, the forEach() method is introduced by the ES5.1 standard, and you need to test whether the browser supports it.
Set
andArray
Similar, butSet
There is no index, so the first two parameters of the callback function are the elements themselves:
var s = new Set(['A', 'B', 'C']); (function (element, sameElement, set) { alert(element); });
Map
The callback function parameters arevalue
、key
andmap
itself:
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]); (function (value, key, map) { alert(value); });
If you are not interested in certain parameters, since JavaScript's function calls do not require that the parameters must be consistent, they can be ignored. For example, just need to obtainArray
ofelement
:
var a = ['A', 'B', 'C']; (function (element) { alert(element); });