📜  typescript for loop - Javascript (1)

📅  最后修改于: 2023-12-03 14:48:04.630000             🧑  作者: Mango

TypeScript for Loop - Javascript

In Javascript, for loops are used to iterate over arrays or objects. Typescript, being a superset of Javascript, also supports for loops with some added features.

Syntax
for (initialization; condition; increment) {
  // code to be executed
}

Initialization: This is where you declare and initialize the for loop variable.

Condition: This is the condition that is checked before each iteration of the loop.

Increment: This is the statement that is executed at the end of each iteration of the loop.

Example
let cars: Array<string> = ['Volvo', 'BMW', 'Mercedes'];
for (let i = 0; i < cars.length; i++) {
  console.log(cars[i]);
}

In this example, we declare an array cars and use a for loop to iterate over its elements.

The initialization declares let i = 0, which initializes the loop variable at 0. The condition i < cars.length checks if the loop variable is less than the length of the array. The increment i++ increases the loop variable by 1 after each iteration of the loop.

The output will be:

Volvo
BMW
Mercedes
For...in loop

Typescript also supports for...in loops, which can be used to iterate over the properties of objects.

let car = {make: 'Volvo', model: 'XC90', year: 2019};
for (let prop in car) {
  console.log(`${prop} = ${car[prop]}`);
}

In this example, we declare an object car and use a for...in loop to iterate over its properties.

The output will be:

make = Volvo
model = XC90
year = 2019
Conclusion

For loops are powerful tools in both Javascript and Typescript, allowing us to iterate over arrays and objects with ease. The added features of Typescript make it even more convenient for iterating through arrays and objects in a type-safe manner.