ECMAScript 6 has become increasingly popular, after more than 20 years of improvement, many features have more mature statements, such as for loop
This blog will introduce four ways to traverse from the initial for loop to the ES6 for-of.
Define an array first:
Const MYARRAY = [1, 5, 9];myarray.name = ' wise '
Print this array in the console and you will see the full picture of this array:
First, for
Trust most developers, the first way to iterate through an array is to use a For loop:
for (Let i = 0; i < myarray.length; i++) { console.log (myarray[i]);}
As a first-generation looping statement, the For statement only solves the traversal function, but the verbose code is too cumbersome
Second, for-in
For-in is much lighter than the for statement, but For-in is usually used to traverse the object, if the array is traversed ...
For (let key in MyArray) { console.log (key);}
If you traverse directly, the index of the array is printed, and index is the string type
If you do not pay attention when programming, it is possible to inadvertently make a string calculation: "1" + "1" = "11"
So the correct posture for traversing an array using for-in should be:
For (let key in MyArray) { console.log (Myarray[key]);}
Unlike for loops, the for-in statement also prints the value "wise" of the custom property "name"
So use for-in to iterate over the array, or do not do it at the time of development.
Third, ForEach
After ES5 was released, JS added the built-in method, ForEach, which is really a good way to iterate through an array:
Myarray.foreach (function (value) { console.log (value);});
But the nature of ForEach is still a method, not a statement
So it does not respond to break, continue, and return statements
Iv. for-of
Carefully analyze the above three methods, if it is limited to traversing arrays, it seems that the original for statement is the most appropriate
Until ES6 turned out, the new circular statement for-of began to emerge.
For (let key of MyArray) { console.log (key);}
Yes, for-of is the most straightforward and refreshing way to iterate through an array.
If the difference between for-in and for-of is summed up in a sentence, it is:
For-in loops are used to iterate through the object properties, for-of loops to traverse the data
Five, for-of not only so
As a ES6 new statement, the combination of for-of and other ES6 grammars is the strength of it.
Traverse Set Type:
Const MYSET = new Set (' Wwiissee '); (let value of MySet) { console.log (value);}
Traverse the Map type:
Const MYMAP = new Map ([' name ', ' Wise '], [' info ', ' wrong '], [' Home ', ' cnblogs ']]); for (let [key, value] of M YMAP) { console.log (key + ' is ' + value);}
"JavaScript" for loop evolutionary history