소프트웨어 이론교육/웹 프로그래밍 기본

Javascript (9) - 배열 및 인덱스

마루설아 2022. 7. 27. 10:41
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        var saramList = [
            {no: 1011, name: '홍길동', score: 100},
            {no: 1022, name: '김길동', score: 80},
            {no: 1053, name: '이길동', score: 90},
            {no: 1044, name: '박길동', score: 95},
            {no: 1055, name: '강길동', score: 75},
        ];

        // saramList에서 no가 1053인 요소가 위치한 index 찾기 방법
        function test01(){
            var saram = null;
            for(var i=0; i<saramList.length; i++){
                if(saramList[i].no == 1053){
                    saram = saramList[i];
                }
            }
            console.log(saram);
        }

        function test02(){
            var saram = null;
            saramList.forEach(function(item, i){  
                if(item.no == 1053){
                        saram = item;
                    }
            });
            console.log(saram);
        }

        function test03(){
            var list = saramList.filter(function(item){
                return item.no == 1053;
            });
            // 조건에 맞는 항목이 list 배열에 push
            console.log(list);
        }

        function test04(){
            var idx = saramList.findIndex(function(item){
                return item.no == 1053;
            });
            console.log("idx =>" + idx);
            
            // 검색 한 idx 위치를 삭제
            saramList.splice(idx, 1);
            console.log(saramList);
        }

        //test01();
        //test02();
        //test03();
        test04();
    </script>
</body>
</html>