[JQuery] 제이쿼리 반복문

Ga0·2023년 8월 1일
0

기타

목록 보기
7/14

"항상 기본적이 반복문(for, foreach)만 쓰다가 오늘 jQuery반복문 존재에 대해 알게 되었다.
생소했기 때문에 정리하고자 한다."

반복문(JQuery)

  • 반복문 : 특정한 작업을 반복하는 것을 의미

예시

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        table, td{ border: 1px solid #333;}
        div{display: flex; margin: 10px 10px;}
    </style>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="forFunc()">for문 실행</button>
    <button onclick="forEachFunc()">forEach문 실행</button>
    <button onclick="dollorForFunc()">$.Each문 실행</button>

    <div>
        <div style="display: block;">
            <div>For문</div>
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">NO</th>
                        <th style="width: 50px;">이름</th>
                        <th style="width: 50px;">나이</th>
                    </tr>
                </thead>
                <tbody id ="forFuncOut">
                </tbody>
            </table>
        </div>
        <div style="display: block;">
            <div>ForEach문(1)</div>
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">NO</th>
                        <th style="width: 50px;">이름</th>
                        <th style="width: 50px;">나이</th>
                    </tr>
                </thead>
                <tbody id ="forEachFuncOut1">
                </tbody>
            </table>
        </div>
        <div style="display: block;">
            <div>ForEach문(2)</div>
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">NO</th>
                        <th style="width: 50px;">이름</th>
                        <th style="width: 50px;">나이</th>
                    </tr>
                </thead>
                <tbody id ="forEachFuncOut2">
                </tbody>
            </table>
        </div>
        <div style="display: block;">
          <div>$.Each문(1)</div>
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">NO</th>
                        <th style="width: 50px;">이름</th>
                        <th style="width: 50px;">나이</th>
                    </tr>
                </thead>
                <tbody id ="dollorForFuncOut1">
                </tbody>
            </table>
        </div>
        <div style="display: block;">
            <div>$.Each문(2)</div>
              <table>
                  <thead>
                      <tr>
                          <th style="width: 50px;">NO</th>
                          <th style="width: 50px;">이름</th>
                          <th style="width: 50px;">나이</th>
                      </tr>
                  </thead>
                  <tbody id ="dollorForFuncOut2">
                  </tbody>
              </table>
          </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script>
        var array = [{name : '이준호', age : 33},
        {name : '임윤아', age : 33},
        {name : '한소희', age : 28},
        {name : '조나단', age : 23},
        {name : '박나래', age : 37},
        {name : '전현무', age : 45},
        {name : '김완선', age : 54}];
        
        function forFunc(){
            var result = ""
            //for문
            for(var i = 0; i < array.length; i++){
                result += `<tr>
                                <td class="forNo">${i}</td>
                                <td class="forName">${array[i].name}</td>
                                <td class="forAge">${array[i].age}</td> 
                            </tr>`
            };

            document.querySelector('#forFuncOut').innerHTML = result;
        }

        
        function forEachFunc(){
            var result1 = "";
            var result2 = "";

            //foreach문
            array.forEach((o, i) => {
                result1 += `<tr>
                                <td class="fENo">${i}</td>
                                <td class="forName">${o.name}</td>
                                <td class="forAge">${o.age}</td> 
                            </tr>`
            });

            document.querySelector('#forEachFuncOut1').innerHTML = result1;
        
            array.forEach(function(o, i){
                result2 += `<tr>
                                <td class="fENo">${i}</td>
                                <td class="forName">${o.name}</td>
                                <td class="forAge">${o.age}</td> 
                            </tr>`
            })
            document.querySelector('#forEachFuncOut2').innerHTML = result2;
            
        }
        
        function dollorForFunc(){
            var result1 = "";
            var result2 = "";

            //&.each문
            $.each(array, function(i, o){
                result1 += `<tr>
                                <td class="eachNo">${i}</td>
                                <td class="forName">${o.name}</td>
                                <td class="forAge">${o.age}</td> 
                            </tr>`
            });

            document.querySelector('#dollorForFuncOut1').innerHTML = result1;
        
            $.each(array, (i, o) => {
                result2 += `<tr>
                                <td class="eachNo">${i}</td>
                                <td class="forName">${o.name}</td>
                                <td class="forAge">${o.age}</td> 
                            </tr>`
            })

            document.querySelector('#dollorForFuncOut2').innerHTML = result2;
        }
        </script>
</body>
</html>

출력값

정리

var array = [{name : '이준호', age : 33},
{name : '임윤아', age : 33},
{name : '한소희', age : 28},
{name : '조나단', age : 23},
{name : '박나래', age : 37},
{name : '전현무', age : 45},
{name : '김완선', age : 54}];

// for문 
/*
    - 가장 기본인 형태의 for문이다.
    - 객체를 요소로 갖는 배열의 인덱스 값을 주어 해당 인덱스의 객체 값의 필드를 출력한다.
*/
for(var i = 0; i < array.length; i++){
    console.log("이름 : "+array[i].name);
    console.log("나이 : "+array[i].age);
}


//forEach문
/*
    - 화살표 형태로 코드를 간결하게 만들 수 있다.
*/
array.forEach((o, i) => {
    // 여기서 o는 배열의 각각의 요소들을 순회하며 뽑는다.
    // i 인덱스도 같이 뽑는다.
    console.log("이름 : "+o.name);
    console.log("나이 : "+o.age);
})

//forEach문
/*
    - 위의 forEach와 동일하지만 인덱스는 뽑지 않는다.
*/
array.forEach(o => { //인덱스를 추가하면 ()로 묶어야하고 그게 아니면 괄호로 묶지 않는다. (이것땜에 에러난 적이 있다...)
    console.log("이름 : "+o.name);
    console.log("나이 : "+o.age);
})

//forEach문
/*
    - forEach문이면서 함수의 원형을 그대로 사용하는 방식이다.
*/
array.forEach(function(o, i){
    console.log("이름 : "+o.name);
    console.log("나이 : "+o.age);
})


//$.each문
/*
    - JQuery 반복문이다.
    - 형태는 forEach와 유사하다.
    - 함수 원형을 사용한 방식이다.
*/
$.each(array, function(o, i){ //반복문 안에 배열의 원본을 넣는다.
    console.log("이름 : "+o.name);
    console.log("나이 : "+o.age);
})

//$.each문
/*
    - 화살표 함수를 사용한 방식이다.
    - 위와 마찬가지로 JQuery 반복문이다.
*/
$.each(array, (o, i) => {
    console.log("이름 : "+o.name);
    console.log("나이 : "+o.age);
})
  • 각각의 반복문을 사용해보았다. (사용하는 문법만 살짝 다를 뿐 결과값은 같다는 것을 확인할 수 있다.)

느낀 점

  • 사실 제이쿼리 반복문은 최근에 알게 되어서 '이런 것도 있구나.' 새로 알게 되었다.
  • 항상 for문이랑 forEach문만 쓰다가 $.each도 앞으로 애용할 것 같다.(사용할 일이 있으면)

0개의 댓글