(SK쉴더스)AI 활용한 클라우드 & 보안 전문가 양성 캠프

[새싹 성동 2기] 학생별 점수 데이터 출력하기

hunm719 2024. 11. 13. 20:26

배열과 객체를 이용한 데이터 처리를 해보자.

//  학생별 점수를 아래 형식에 맞춰서 콘솔에 출력
    
let scores = [];

/*  ### 학생별 점수 데이터
    0: {name: '홍길동', korean: 80, math: 90, english: 90}
    1: {name: '고길동', korean: 90, math: 80, english: 80}
    2: {name: '신길동', korean: 70, math: 80, english: 70}


    ### 출력 형식
    ----------- --------- --------- --------- --------- ---------
    학생이름     국어      영어      수학      합계      평균
    ----------- --------- --------- --------- --------- ---------
    홍길동       80        90        90        260       86.7
        :          :         :         :          :        :
*/
1. 배열 scores 에 데이터 추가
2. 양식에 맞게 console.log 작성
// 1. 배열에 데이터 추가
scores.push({ name : "홍길동", koeran : 80, math : 90, english : 90 });
scores.push({ name : "고길동", koeran : 90, math : 80, english : 80 });
scores.push({ name : "신길동", koeran : 70, math : 80, english : 70 });
console.log(scores);
// 헤더(타이틀)를 출력
console.log(`--------\t----\t----\t----\t----\t----\t`);
console.log(`학생이름\t\t국어\t영어\t수학\t합계\t평균`);
console.log(`--------\t----\t----\t----\t----\t----\t`);

// 학생별 점수를 출력
scores.forEach(score => {
    const total = function () {
        return score.korean + score.english + score.math;
    };

    const average = () => {
        const result = total() / 3;
        // 소수점 둘째 자리에서 반올림해서 반환
        // 123.4567 => 1234.567 => 1235 => 123.5
        return Math.round(result * 10) / 10
    };

    console.log(`${score.name}\t\t${score.korean}\t${score.english}\t${score.math}\t${total()}\t${average()}`);
});

console.log(`--------\t----\t----\t----\t----\t----\t`);

 

※ total 함수 다르게 표현하기

const total = function () {
        return score.korean + score.english + score.math;
    };


위의 코드를 화살표 함수로 만들고 최대한 축약해보자
1. function 키워드를 제거하고, 함수 파라미터와 본문 사이에 화살표 추가
const total = () => { return score.korean + score.english + score.math; }

2. 본문이 한 줄이고 => 중괄호 생략 가능
const total = () => return score.korean + score.english + score.math;

3. 본문이 한 줄이면서 그 한 줄이 return 문이고 => return 생략 가능
const total = () => score.korean + score.english + score.math;