Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

항해일지

[항해99] JS 기초 Chapter4 확인 문제 풀기 (반복문) 본문

항해99/온보딩 스터디 문제풀이

[항해99] JS 기초 Chapter4 확인 문제 풀기 (반복문)

효환 2023. 3. 8. 17:38

 

6가지 키워드로 정리하는 핵심 포인트

 

  • for in 반복문은 배열의 인덱스를 기반으로 반복할 때 사용합니다.
  • for of 반복문은 배열의 값을 기반으로 반복할 때 사용합니다.
  • for 반복문은 횟수를 기반으로 반복할 때 사용합니다.
  • while 반복문은 조건을 기반으로 반복할 때 사용합니다.
  • break 키워드는 switch 조건문이나 반복문을 벗어날 때 사용합니다
  • continue 키워드는 반복문 안의 반복 작업을 멈추고 반복문의 처음으로 돌아가 다음 반복 작업을 진행합니다.

 

 


 

 

 

1. 다음 프로그램의 실행 결과를 예측해보세요.

    <script>
        const array = ['사과', '배', '귤', '바나나']
        console.log('# for in 반복문!')
        for (const i in array) {
            console.log(i)
        }

        console.log('# for of 반복문')
        for (const i of array){
            console.log(i)
        }
    </script>

 

 

 

 

 

 

2. 다음 프로그램의 실행 결과를 예측해보세요. 혹시 오류가 발생한다면 어디를 수정해야 할까요?

    <script>
        const array = []
        for (const i = 0; i < 3; i++){
            array.push((i + 3) * 3)
        }
        console.log(array)
    </script>

에러코드 : index.html:13 Uncaught TypeError: Assignment to constant variable. at index.html:13:35
   
  오류 수정 : i는 값이 변해야 하기때문에 상수가 아니라 변수로 선언해야한다.
   <script>
        const array = []
        for (let i = 0; i < 3; i++){
            array.push((i + 3) * 3)
        }
        console.log(array)
    </script>

 

 

 

 

3. 1부터 100까지의 숫자를 곱한 값을 계산하는 프로그램을 만들어보세요. 그리고 코드를 실행해 나온 결과를 확인해보세요.

    <script>
        let output = 1

        for(i = 1; i < 101; i++ ){
            output = output * i
        }
        console.log(`1 ~ 100의 숫자를 모두 곱하면, ${output}입니다.`)
    </script>

 

 

 

 

4. 처음에는 조금 어려울 수 있겠지만, 활용 예제의 피라미드를 활용해서 다음과 같은 피라미드를 만들어 보세요.

    <script>
        let output = ''
        const size = 5
        for (let i = 1; i < size; i++) {
            for (let j = size; j > i; j--) {
                output = output + ' '
            }
            for (let z = 0; z < 2 * i - 1; z++) {
                output = output + '*'
            }
            output =  output + '\n'  
        }

        for(let i = size; i > 0; i--){
            for(let j = size; j > i; j--){
                output = output + ' '
            }
            for(let z = 0; z < 2 * i - 1; z++){
                output = output + "*"
            }
            output =  output + '\n'  
        }
        console.log(output)
    </script>


Comments