1. for () {}
var arr = [1,2,3,4,5];for (let i=0; i<arr.length; i++) { //... }
Cons: Code But concise
2. ForEach ()
var arr = [1,2,3,4,5];arr.foreach (function (value,index) { //...});
Disadvantage: Cannot interrupt stop the entire loop
3, for...in
var arr = [1,2,3,4,5];for (Let me in arr.) { //... }
Note: for...in loops are more commonly used for "object" loops, and if you are using loops for "arrays", the I that gets in each loop is "string type" rather than the expected number type, which is the first type conversion to be performed.
4, For...of
var arr = [1,2,3,4,5];for (let value of arr) { console.log (value);//1 2 3 4 5 }
Note: The ① is more concise than the For loop, ② can use break to terminate the entire loop, or continue to jump out of the loop, continue to the back loop, ③ combine keys () to get the index of the loop, and the number type, not the string type.
* Cycle can be terminated
var arr = [1,2,3,4,5];for (let value of arr) { if (value = = 3) {break ; } Console.log (value); } Printed results: 1 2
* Skip the current loop
var arr = [1,2,3,4,5];for (let value of arr) { if (value = = 3) { continue; } Console.log (value); } Printed results: 1 2 4 5
* Get index of number type
var arr = [1,2,3,4,5];for (Let Index of Arr.keys ()) { console.log (index); } Printed results: 0 1 2 3 4
Ways to iterate over an array