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 items = ["item1", "item2", "item3"]
2var copie = [];
3
4items.forEach(function(item){
5 copie.push(item);
6});
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});
1const marks = [12, 17, 14];
2let sum = 0;
3
4marks.forEach(mark => {
5 sum += mark;
6});