In the JavaScript Array.prototype.forEach()
method, you can get the index of the current element in the loop by using the (optional) second parameter of the callback function, for example, like so:
const arr = ['apple', 'banana', 'orange']; arr.forEach((item, index) => { console.log(`${index}: ${item}`); });
In this example, the callback function to Array.prototype.forEach()
method has two parameters (i.e. the current element and its index). It produces the following output:
// '0: apple' // '1: banana' // '2: orange'
Hope you found this post useful. It was published . Please show your love and support by sharing this post.