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});
1const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
2
3// Iterate over fruits below
4
5// Normal way
6fruits.forEach(function(fruit){
7 console.log('I want to eat a ' + fruit)
8});
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
1let words = ['one', 'two', 'three', 'four'];
2words.forEach((word) => {
3 console.log(word);
4});
5// one
6// two
7// three
8// four
1var stringArray = ["first", "second"];
2
3myArray.forEach((string, index) => {
4 var msg = "The string: " + string + " is in index of " + index;
5 console.log(msg);
6
7 // Output:
8 // The string: first is in index of 0
9 // The string: second is in index of 1
10});