배열에 객체 저장- 10.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

배열에 객체 저장

   

학습내용

자바와 유사

동일한 패턴 사용시

   

소스 코드

   

  1. <script type="text/javascript">
  2.         //생성자 함수
  3.         function Student(name, korean, math, english, science){
  4.                 //속성 지정
  5.                 //this 전역변수로 this없으면 지역변수
  6.                 this.name = name;
  7.                 this.korean = korean;
  8.                 this.math = math;
  9.                 this.english = english;
  10.                 this.science = science;
  11.                  
  12.                 //메소드 지정
  13.                 this.getSum = function(){
  14.                         return this.korean + this.math + this.english + this.science;
  15.                 };
  16.                 this.getAverage = function(){
  17.                         return this.getSum()/4;
  18.                 };
  19.                 this.toString = function(){
  20.                         return this.name + ', ' + this.getSum() + ', ' + this.getAverage();
  21.                 };             
  22.         }
  23.          
  24.         var students = [];
  25.         students.push(new Student('홍길동', 99, 88, 55, 66));
  26.         students.push(new Student('일지매', 99, 77, 67, 78));
  27.         students.push(new Student('대장금', 45, 65, 65, 87));
  28.         students.push(new Student('금잔디', 99, 88, 55, 66));
  29.         students.push(new Student('하회탈', 99, 88, 55, 66));
  30.         students.push(new Student('곰탱이', 99, 80, 55, 66));
  31.          
  32.         //출력
  33.         var output = '이름, 총점, 평균\n';
  34.         for(var i in students){
  35.                 output += students[i].toString() + '\n';
  36.         }
  37.         alert(output);
  38. </script>
  39. </head>
  40. <body>
  41.    
  42. </body>


   

 

출력결과

   

반응형