There are a few methods that can be used to Iterate an Array.
forEach() Function is used to call a function as many times as that of the Array elements.
Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.
And we want to call a function at each iteration.
And forEach() helps us achieve the above.
Let us see in the below example.
<html> <body> <script> function numberCheck(element) { document.write(element, "</br>") } var x = [5, 8, 2, 81, 9] x.forEach(numberCheck) </script> </body> </html>
So, we have an Array that has 5 numbers.
And we have defined a function called numberCheck(), that prints the values of the array.
function numberCheck(element) { document.write(element, "</br>") }
And we have called the above function from map() function.
var y = x.map(numberCheck)
And forEach() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.
x.forEach(numberCheck)
And it prints the values of the Array
Again, let us say, we want to display the values of the array along with its indexes.
Luckily, forEach() function allows us to achieve that as well.
Let us see in the below example.
<html> <body> <script> function numberCheck(element, index) { document.write(index, " --> ", element, "</br>") } var x = [5, 8, 2, 81, 9] x.forEach(numberCheck) </script> </body> </html>
So, the first argument in the forEach() function is the actual value and the second argument is the index of it.
And accordingly, we have defined the function.
function numberCheck(element, index) { document.write(index, " --> ", element, "</br>") }
And called it from forEach(),
x.forEach(numberCheck)
Similarly, map() function can be used to Iterate Array elements.
map() Function is used to create a new array with the results from the function called.
Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.
And we want to have an array with all the values with two added to it.
i.e. The first element 5 should be added with 2 and become 7.Similarly, the second element 8 would be added with 2 and become 10.
Continuing this way, we should get an Array with the below values.
And map() helps us achieve the above array.
Let us see in the below example.
<html> <body> <script> function numberCheck(i) { return i+2 } var x = [5, 8, 2, 81, 9] var y = x.map(numberCheck) document.write(y) </script> </body> </html>
So, we have an Array that has 5 numbers.
And we want to construct an array with all the values incremented by 2.
We have defined a function called numberCheck(), that increments all the values by 2.
function numberCheck(i) { return i+2 }
And we have called the above function from map() function.
var y = x.map(numberCheck)
And map() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.
var y = x.map(numberCheck)
And it increments all the values of the Array by 2 and forms a new Array.
And the new array is printed as output.
7,10,4,83,11