본문 바로가기
JSP/Muzi

[Javascript] 배열식 접근법

by 미눅스[멘토] 2024. 8. 26.
728x90
<!DOCTYPE html>
<meta charset="UTF-8">
<body>
    <div id="disp"></div>
</body>
<script>
const hdisp = document.querySelector('#disp');

let members = [
    {name:"김수지",level:"pos1"},
    {name:"임석일",level:"pos2"},
    {name:"강서주",level:"pos3"},
    {name:"이경민",level:"pos3"},
    {name:"신진수",level:"pos2"},
]

let levels = {
    "pos1":"대표님",
    "pos2":"전무님",
    "pos3":"사원님",
}

let tblStr = "<table border=1>";
    tblStr +="<tr><th>넘버</th><th>이름</th><th>직급</th></tr>"

    for(let i=0; i<members.length; i++) {
        tblStr += "<tr>";
        tblStr += `<td>${i+1}</td>`;
        tblStr += `<td>${members[i].name}</td>`;

        // 배열식 접근법이 존재해서 아주 쉽게 해결할 수 있음
        tblStr += `<td>${levels[members[i].level]}</td>`;
        tblStr += `</tr>`;
    }
    tblStr += "</table>";
    
    hdisp.innerHTML = tblStr;

    console.log(levels['pos1']);
    console.log(levels[0]);
</script>