2

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

1
  • What does this have to do with typescript? Commented Dec 13, 2019 at 4:57

1 Answer 1

3

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])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.