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
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///Simple One
2var a = ["a", "b", "c"];
3a.forEach(function(entry) {
4 console.log(entry);
5});
6
7
8///Function concept
9
10var fruits = ["apple", "orange", "cherry"];
11fruits.forEach(myFunction);
12
13function myFunction(item, index) {
14 document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
15}
16
1const avengers = ['IronMan','thor', 'captain america', 'hulk'];
2avengers.forEach((item, index)=>{
3 console.log(index, item)
4})