In TypeScript, you can iterate over an array using various methods. Here are a few examples:
For Loop:
typescriptlet myArray: number[] = [1, 2, 3, 4, 5];
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
For...of Loop:
typescriptlet myArray: number[] = [1, 2, 3, 4, 5];
for (let element of myArray) {
console.log(element);
}
forEach Method:
typescriptlet myArray: number[] = [1, 2, 3, 4, 5];
myArray.forEach((element) => {
console.log(element);
});
Map Method:
typescriptlet myArray: number[] = [1, 2, 3, 4, 5];
myArray.map((element) => {
console.log(element);
// Map returns a new array, but if you just want to iterate, use forEach
});
Using indexes with forEach:
typescriptlet myArray: number[] = [1, 2, 3, 4, 5];
myArray.forEach((element, index) => {
console.log(`Index: ${index}, Element: ${element}`);
});
Choose the method that fits your needs best based on the specific requirements of your code. The forEach
method is often preferred for simple iteration over arrays due to its concise syntax.