In the process of writing code using JavaScript, multiple methods can be used to traverse the array; including for loops, forEach loops, map loops, forIn loops, and forOf loops and other methods.
1. For loop: basic, simple
This is the most basic and commonly used method of traversing arrays; various development languages generally support this method.
let arr = ['a','b','c','d','e']; for (let i = 0, len = ; i < len; i++) { (i); // 0 1 2 3 4 (arr[i]); //a b c d e }
2. forEach() method: use callback function
forEach() This is a method of an array object; it accepts a callback function as an argument.
There are three parameters in the callback function:
- 1st: Array elements (required)
- 2nd: array element index value (optional)
- 3rd: The array itself (optional)
let arr = ['a','b','c','d','e']; ((item,index,arr)=> { (item); // a b c d e (index); // 0 1 2 3 4 (arr); // ['a','b','c','d','e'] })
3. map() method: use callback function
It is used the same as the forEach() method.
var arr = [ {name:'a',age:'18'}, {name:'b',age:'19'}, {name:'c',age:'20'} ]; (function(item,index) { if( == 'b') { (index) // 1 } })
4. for..in loop: traverse objects and arrays
for…in loops can be used to loop objects and arrays.
It is recommended for looping objects, and can also be used to traverse json.
let obj = { name: 'Wang Daehn', age: '18', weight: '70kg' } for(var key in obj) { (key); // name age weight (obj[key]); // Wang Daehui 18 70kg} ---------------------------- let arr = ['a','b','c','d','e']; for(var key in arr) { (key); // 0 1 2 3 4 Return the array index (arr[key]) // a b c d e }
5. for…of loop: traverse objects and arrays
Loopable arrays and objects, recommended for traversing arrays.
for…of provides three new methods:
- key() is a traversal of key names;
- value() is a traversal of key values;
- entries() is a traversal of key-value pairs;
let arr = ['iFlytek', 'Political and Legal BG', 'Front-end development']; for (let item of arr) { (item); // iFlytek Political and Legal BG Front-end Development} // Output array indexfor (let item of ()) { (item); // 0 1 2 } // Output content and indexfor (let [item, val] of ()) { (item + ':' + val); // 0: iFLYTEK 1: Political and Legal BG 2: Front-end development}
6. Supplement
6.1. Break and Continue issues
existforEach、map、filter、reduce、every、some
In the functionbreak
and continue
The keywords will not take effect because they are in the function, but the function solves the problem of closure traps.
If you want to use break or continue, you can use itfor、for...in、for...of、while
。
6.2. Arrays and Objects
Used to traverse array elements:for(),forEach(),map(),for...of
。
Used for loop object properties:for...in
。
The above is the detailed content of the five methods of JavaScript array traversal. For more information about JavaScript array traversal, please pay attention to my other related articles!