배열과 객체의 사용- 07.html

CODEDRAGON Development/JavaScript, jQuery, ...

반응형

   

배열과 객체의 사용

객체를 최소로 만들고,

배열의 객체에 접근해서 동적으로 배열 요소 추가

   

학습내용

자바에는 없는 형태

패턴이 바뀔 경우

   

소스 코드

   

  1. <script type="text/javascript">
  2.         // 객체 생성
  3.         var students = [];
  4.          
  5.         //객체를 배열에 저장
  6.         students.push( { name:'홍길동', korean:90, math:70, english:89, science:80 } );
  7.         students.push( { name:'이순신', korean:95, math:79, english:78, science:87 } );
  8.         students.push( { name:'유관순', korean:100, math:96, english:67, science:67 } );
  9.         students.push( { name:'일지매', korean:89, math:85, english:87, science:98 } );
  10.         students.push( { name:'대장금', korean:99, math:97, english:96, science:88 } );
  11.          
  12.         //students배열내의 모든 객체에 메소드 추가
  13.         for(var i in students){
  14.                 //총점 구하는 메소드 추가
  15.                 students[i].getSum = function(){
  16.                         return this.korean + this.math + this.english + this.science;
  17.                 };
  18.                  
  19.                 //평균 구하는 메소드 추가
  20.                 students[i].getAverage = function(){
  21.                         return this.getSum()/4;                
  22.                 };             
  23.         }
  24.          
  25.         //출력
  26.         var output = "이름, 총점, 평균\n";
  27.         for(var i in students){
  28.                 output += students[i].name + ' , ' + students[i].getSum() + ', ' +students[i].getAverage() + '\n';
  29.         }
  30.          
  31.         alert(output);
  32.          
  33. </script>
  34. </head>
  35. <body>
  36.    
  37. </body>

 

   

출력결과

   

   

반응형