1var data = [1, 2, 3, 4, 5, 6];
2
3// traditional for loop
4for(let i=0; i<=data.length; i++) {
5 console.log(data[i]) // 1 2 3 4 5 6
6}
7
8// using for...of
9for(let i of data) {
10 console.log(i) // 1 2 3 4 5 6
11}
12
13// using for...in
14for(let i in data) {
15 console.log(i) // Prints indices for array elements
16 console.log(data[i]) // 1 2 3 4 5 6
17}
18
19// using forEach
20data.forEach((i) => {
21 console.log(i) // 1 2 3 4 5 6
22})
23// NOTE -> forEach method is about 95% slower than the traditional for loop
24
25// using map
26data.map((i) => {
27 console.log(i) // 1 2 3 4 5 6
28})
1const myArray = ['foo', 'bar'];
2
3myArray.forEach(x => console.log(x));
4
5//or
6
7for(let i = 0; i < myArray.length; i++) {
8 console.log(myArray[i]);
9}
10
1/* ES6 */
2const cities = ["Chicago", "New York", "Los Angeles"];
3cities.map(city => {
4 console.log(city)
5})
6
1let arbitraryArr = [1, 2, 3];
2// below I choose let, but var and const can also be used
3for (let arbitraryElementName of arbitraryArr) {
4 console.log(arbitraryElementName);
5}
1int[] objects = {
2 "1", "2", "3", "4", "5"
3};
4
5for (int i = 0; i < objects.length; i++) {
6 System.out.println(objects[i]);
7}