Reputation: 3880
I know there a lot of answers about looping x amount of times on javascript but i'm finding if there any way to loop x amount of times in a typescript for..of
loop function on an array, until now i haven't able to look up any answer involving the for..of
function . Example:
const someArray = [1, 2, 3, 4, 5, 6, 7];
for(let i of someArray) {
console.log(i);
}
//loop result are from 1 to 7
//i would like the loop to run 3 times so expected result to be 1, 2, 3
What i'm looking for is to run the loops only 3 times
and apply to the for...of
function of typescript
I'm still a novice at typescript
Upvotes: 2
Views: 9412
Reputation: 84912
To loop through the first elements of an array in javascript, use a standard for loop, and end the loop counter at 3:
for (let i = 0; i < 3; i++) {
console.log(someArray[i])
}
Typescript does not change anything here, except give you the option to be explicit that the loop counter is a number.
for (let i: number = 0; i < 3; i++) {
console.log(someArray[i])
}
Upvotes: 3