1const avengers = ['thor', 'captain america', 'hulk'];
2avengers.forEach((item, index)=>{
3 console.log(index, item)
4})
1var colors = ['red', 'blue', 'green'];
2
3colors.forEach(function(color) {
4 console.log(color);
5});
1/** 1. Use forEach and related */
2var a = ["a", "b", "c"];
3a.forEach(function(entry) {
4 console.log(entry);
5});
6
7/** 2. Use a simple for loop */
8var index;
9var a = ["a", "b", "c"];
10for (index = 0; index < a.length; ++index) {
11 console.log(a[index]);
12}
13
14/**3. Use for-in correctly*/
15// `a` is a sparse array
16var key;
17var a = [];
18a[0] = "a";
19a[10] = "b";
20a[10000] = "c";
21for (key in a) {
22 if (a.hasOwnProperty(key) && // These checks are
23 /^0$|^[1-9]\d*$/.test(key) && // explained
24 key <= 4294967294 // below
25 ) {
26 console.log(a[key]);
27 }
28}
29
30/** 4. Use for-of (use an iterator implicitly) (ES2015+) */
31const a = ["a", "b", "c"];
32for (const val of a) {
33 console.log(val);
34}
35
36/** 5. Use an iterator explicitly (ES2015+) */
37const a = ["a", "b", "c"];
38const it = a.values();
39let entry;
40while (!(entry = it.next()).done) {
41 console.log(entry.value);
42}
43
1var array = ["a","b","c"];
2// example 1
3 for(var value of array){
4 console.log(value);
5 value += 1;
6 }
7
8// example 2
9 array.forEach((item, index)=>{
10 console.log(index, item)
11 })
1const numList = [1, 2, 3];
2
3numList.forEach((number) => {
4 console.log(number);
5});