Computer >> Computer tutorials >  >> Programming >> Javascript

Execute digits in even places in a JavaScript array?


To access the numbers from the even places, rather than looping through the numbers, loop through the places i.e indexes. If we loop through the numbers, other than the elements in the even places, even numbers will be accessed. 

Example

In the following example, a for- loop is used to loop through all the positions and an empty string is used to access the even place values. The conditional statement "if" is used to check whether the positions are even or not. If any position is even then the value corresponding to that position is accessed through the empty string and displayed as shown in the output.

<html>
<body>
<script>
   var nums = [15,23,63,53,58,66,77,29,2,110];
   for(var i = 0; i< nums.length; i++) {
      var dis = "";
      if((i + 1) %2 === 0) {
         dis = dis + (nums[i]) + "</br>";
         document.write("Digit in " +(i + 1)+ " place is " + " "+dis);
      }
   }
</script>
</body>
</html>

Output

Digit in 2 place is 23
Digit in 4 place is 53
Digit in 6 place is 66
Digit in 8 place is 29
Digit in 10 place is 110