TypeScript에서 반복문(Loop) 을 사용하는 2가지 방법을 알아본다
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
for (const pl of plArr) {
console.log(`${pl}`);
}
[Result]
Java
Kotlin
Typescript
Javascript
const numArr: any = [1, 3, 5, 7, 9];
for (const num of numArr) {
console.log(`${num}`);
}
[Result]
1
3
5
7
9
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
for (const idx in plArr) {
const content: string = plArr[idx];
console.log(`${content} : ${idx}`);
}
[Result]
Java : 0
Kotlin : 1
Typescript : 2
Javascript : 3
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
// arr === plArr
plArr.forEach((value, index, arr) => {
console.log(`${value} : ${index}`);
});
[Result]
Java : 0
Kotlin : 1
Typescript : 2
Javascript : 3
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
for (let idx = 0; idx < plArr.length; idx++) {
const content: string = plArr[idx];
console.log(`${content} : ${idx}`);
}
[Result]
Java : 0
Kotlin : 1
Typescript : 2
Javascript : 3
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
let idx: number = 0;
while(idx < plArr.length) {
const content: string = plArr[idx];
console.log(`${content} : ${idx}`);
idx++;
}
[Result]
Java : 0
Kotlin : 1
Typescript : 2
Javascript : 3
const plArr: any = ['Java', 'Kotlin', 'Typescript', 'Javascript'];
let idx: number = 0;
do {
const content: string = plArr[idx];
console.log(`${content} : ${idx}`);
idx++;
} while(idx < plArr.length)
[Result]
Java : 0
Kotlin : 1
Typescript : 2
Javascript : 3