loop over an array with an index in typescript

Here's an example of how to loop through an array with an index using a for...of loop in TypeScript:

index.ts
const myArray = ['apple', 'banana', 'orange'];

for (let i = 0; i < myArray.length; i++) {
  console.log(i, myArray[i]);
}
123 chars
6 lines

Output:

index.ts
0 "apple"
1 "banana"
2 "orange"
32 chars
4 lines

Alternatively, you could use a for...of loop to achieve the same result:

index.ts
const myArray = ['apple', 'banana', 'orange'];

for (const [index, value] of myArray.entries()) {
  console.log(index, value);
}
129 chars
6 lines

Output:

index.ts
0 "apple"
1 "banana"
2 "orange"
32 chars
4 lines

The entries() method returns an iterator that produces an array of [index, value] pairs for each element in the array. Using destructuring, we can assign each pair to variables inside the loop.

gistlibby LogSnag