JavaScript 19일차

펭도리·2021년 2월 21일
0

JavaScript

목록 보기
19/32
post-thumbnail
     <script>
        function Student(name, korean, math, english ,science) {
            this.이름 = name,
            this.국어 = korean,
            this.수학 = math,
            this.영어 = english,
            this.과학 = science
        }

        Student.prototype.getSum = function() {
            return this.국어 + this.수학 + this.영어 + this.과학;
        }

        Student.prototype.getAverage = function() {
            return this.getSum() / 4;
        }

        Student.prototype.toString = function() {
            return this.이름 + '\t' + this.getSum() + '\t\t' + this.getAverage() + '\n';
        }

        var students = [];
        students.push(new Student('쭈쭈',100,70,90,70));
        students.push(new Student('뭉치',60,100,20,100));
        students.push(new Student('땅콩',100,100,100,100));
        students.push(new Student('보리',80,100,100,100));

        students.sort(function(left,right) {
            return right.getSum() - left.getSum();
        });

        // 1~3등까지만 배출.
        students = students.slice(0,3);
        /* 1~3등까지 배출.
            students.sort(function(left,right) {
            return right.getSum() - left.getSum();
        }).sort(0,3);
        */

        var output = '이름\t총점\t평균\n\n';
        for(var i in students) {
            output += students[i].toString() + '\n';
        }

        console.log(output);
    </script>
    
    output
    이름   총점   평균

    땅콩   400   100

    보리   380    95

    쭈쭈   330   82.5  

각각 인원들 마다 getSum()함수를 공용적으로 사용하게 된다.

sort() 메서드를 통해 내림차순으로 정렬하여 등수를 정하였다.

     <script>
        Array.prototype.remove = function(index) {
            this.splice(index, 1);
        }

        var array = [52, 273, 103, 32, 274, 129];

        for(var i in array) {
            if(array[i] > 100) {
                array.remove(i);
            }
        } 
        // 여기까지의 결과값 = 52 103 32 129가 나온다. 
        // 이유는 273이 사라지면서 한칸씩 좌로 이동하기 때문에 103은 검열받지 않는다.
        // 따라서 역 반복문을 사용해야 한다.

        // for(var i = array.length-1; i >= 0; i--) {
        //     if(array[i] > 100) {
        //         array.remove(i);
        //     }
        // }
        

        console.log(array);
    </script>

for(var i in array)의 결과값으로는 [52, 103, 32, 129]가 출력된다.

이유는 273이 remove되면서 배열이 좌측으로 한칸씩 땡겨지기 때문에 103이 if문의 검열을 받지 않기 때문이다. 129 또한 마찬가지이다.

이를 해결하기 위해서는 역방향으로 반복문을 돌려주어야 한다. 그렇게되면 remove되더라도 다시 끝에서부터 검열하기 때문에 정확하게 걸러낼 수 있다.

forEach

	var array = [1,2,3,4,5,6,7,8,9,10];

        var sum = 0;
        var output = '';
        array.forEach(function(element,index,array) {
            sum += element;
            output += index + ': ' + element + ' -> ' + sum + '\n';
            // index = 배열이 몇번째 순서인지 나타낸다.
            // element = 배열의 요소를 나타낸다.
            // array = 배열 그자체를 나타낸다.
        });

        console.log(output);

forEach는 그 배열을 전체 순환한다.
element : 배열의 요소
index : 몇번째 배열인지
array : 배열 그 자체를 나타낸다.

map

	var array = [1,2,3,4,5,6,7,8,9,10];

        var output = array.map(function (element) {
            return element * element;
        });

        console.log(output)
        console.log(array) 
        // map는 새로운 배열을 만들기 때문에 기존의 array의 배열은 바뀌지 않는다.

map은 filter 또는 reduce 와 같은 메서드와 함께 활용할 수 있다.
예를들면

let result = array.map(e => e).filter(e => e>5);

위와 같은 코드를 살펴보자

filter의 조건으로 요소의 값이 5보다 클때 로 설정되어 있다.(e > 5)
따라서 필터에 의해 array의 요소는 [6, 7, 8, 9, 10]이 되고 map에 의해 새로운 배열로 반환된다.

profile
풀스택 개발자가 되고싶은 코린이 이한글

0개의 댓글