Syntax error How to get sequence number in loops with JavaScript?

How to get sequence number in loops with JavaScript?



To get sequence number in loops, use the forEach() loop. Following is the code −

Example

let studentDetails =
[
   {
      id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},
      {id:102, details: [{name:'Carol'},{name:'David'},
      {name:'Mike'}]
   }
];
var counter = 1;
studentDetails.forEach(function(k){
   k.details.forEach(function(f) {
         console.log(counter++);
      }
   );
});

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo159.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo159.js
1
2
3
4
5
6
Updated on: 2020-09-12T07:46:59+05:30

975 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements