본문 바로가기

Programming/JavaScript

Looping Backwards and Loops in Loops

const sunnyArray = [
    'Sunny',
    'Ryu',
    2022 - 1988,
    'technical writer',
    ['Writing', 'Coding', 'Learning']
];

// 4, 3, ..., 0

for (let i = sunnyArray.length - 1; i >= 0; i--) {
    console.log(sunnyArray[i]);
}

배열의 마지막 값부터 출력되는 걸 알 수 있음

sunnyArray.length 이 방법이 더 좋은 이유는

배열에 값이 몇 개 있는지 일일히 세서 하드코딩할 필요 없다는 것! 🙅‍♀️

 

Loops in Loops

for (let exercise = 1; exercise <= 4; exercise++) {
    console.log(`------ Starting exercise ${exercise}`);

    for (let rep = 1; rep < 6; rep++) {
        console.log(`Lifting weight repetition ${rep} `);
    }
}

바깥 loop이 돌때마다 안의 loop이 5번씩 반복됨!

 

'Programming > JavaScript' 카테고리의 다른 글

An High-Level Overview of JavaScript  (0) 2022.11.13
Coding Challenge #4 - arrays for the tips and the totals  (0) 2022.11.09
The while Loop  (0) 2022.09.19
Looping Arrays, Breaking and Continuing  (0) 2022.09.19
Iteration: The for Loop  (0) 2022.09.15