본문 바로가기

프로그래밍/자바스크립트

[자바스크립트]객체 : 배열에 객체 저장

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>배열에 객체 저장</title>
<script type="text/javascript">
    //빈 배열 생성
    var students = [];
    
    //객체를 배열에 저장
    students.push({이름:'홍길동',국어:100,영어:90,수학:89,과학:91});
    students.push({이름:'박문수',국어:99,영어:89,수학:88,과학:86});
    students.push({이름:'장영실',국어:97,영어:88,수학:88,과학:85});
    students.push({이름:'김유신',국어:98,영어:86,수학:87,과학:84});
    students.push({이름:'김길동',국어:97,영어:87,수학:86,과학:83});
    students.push({이름:'이순신',국어:93,영어:85,수학:85,과학:90});
    
    //students 배열내의 모든 객체에 메서드 추가
    for(var i in students){
        //총점을 구하는 메서드 추가
        students[i].getSum = function(){
            return this.국어 + this.영어 + this.수학 + this.과학;
        };
        
        //평균을 구하는 메서드 추가
        students[i].getAvg = function(){
            return this.getSum() / 4;
        };
    }
    
    //출력
    var output = '이름, 총점, 평균<br>';
    for (var i in students){
        output += students[i].이름 + ', ' + students[i].getSum() + ', ' + students[i].getAvg()+'<br>'
    }
    
    document.write(output);
    
</script>
//출력 결과
이름, 총점, 평균
홍길동, 370, 92.5
박문수, 362, 90.5
장영실, 358, 89.5
김유신, 355, 88.75
김길동, 353, 88.25
이순신, 353, 88.25
</head>
<body>
 
</body>
</html>
cs