자바스크립트 arrow함수형태 및 reduce함수 질문

조회수 388회
class Student {
    constructor(name, age, enrolled, score) {
        this.name = name;
        this.age = age;
        this.enrolled = enrolled;
        this.score = score;
    }
}
const students = [
    new Student('A', 29, true, 45),
    new Student('B', 28, false, 80),
    new Student('C', 30, true, 90),
    new Student('D', 40, false, 66),
    new Student('E', 18, true, 88)
];

//Q9. compute students average score
let aver =0;
let total =0;
for(let student of students) {
    total += student.score;
     aver = total/students.length;
}

//ellie's solution => reduce 함수 활용
const result9 = students.reduce((prev, curr)=>{
    console.log('------------');
    console.log(prev);
    console.log(curr);
    return prev + curr.score;
}, 0);

여기서 보시면 저는 저렇게 구했고 드림코딩 엘리선생님은 reduce함수를 사용하셨는데 저기서 students의 요소.score를 해야하는 부분을 단순히 prev, curr로 표현하셨는데 이게 이해가 안됩니다. arrow함수 구조는 알고있지만 저런식으로 과정이 많이 생략되서 쓰여지면 정말 모르겠더라구요 .. javascript를 이제껏너무 어깨너머 배우는식으로 배워와서 그런가..;; 알려주세요 ㅠ

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 드림코딩 엘리 선생님은 질문을 절대 안 받으시는 모양이군요. 아무튼 문제의 reduce()는 사실 Array.prototype.reduce()가 쓰인 것입니다. 그 메소드의 자세한 동작 방식이나 원리는 MDN 문서를 확인해 보시고...

    아무튼 문서를 보면, 결국 엘리 선생님의 코드는 다음 코드와 똑같은 것임을 알 수 있습니다.

    let initialValue = 0;
    const result9 = students.reduce(function (accumulator, currentValue) {
        // 콘솔 찍는건 생략
        return accumulator + currentValue.score;
    }, initialValue);
    

    그리고 사실 함수를 정의할 때는 인자 이름을 아무렇게나 지어도 되기 때문에, 위의 코드는 또한 아래의 코드와 똑같습니다.

    let x = 0;
    const result9 = students.reduce(function (foobar, lorem) {
        return foobar + lorem.score;
    }, x);
    

    여기에 화살표 함수를 도입하면 이렇게 될 테고:

    let x = 0;
    const result9 = students.reduce((foobar, lorem) => {
        return foobar + lorem.score;
    }, x);
    

    여기에 의미 있는 인자 이름 사용 + 불필요한 변수 정의 생략 을 하면:

    const result9 = students.reduce((prev, curr) => {
        return prev + curr.score;
    }, 0);
    

    바로 엘리 선생님의 코드 같은 것이 됩니다.
    그리고 확실히 이 코드는 배열의 모든 원소를 특정한 방식으로 가공하여 특정한 1개의 값으로 환원(reduce)시킨다는 목적을 달성함에 있어서 아래 코드보다는 더 명확하고 ('reduce'라는 이름을 통해) 관행 친화적이며 그래서 다른 사람들이 이해하고 따라가기 쉽습니다.

    let total = 0; // 다른 곳에 이 코드 복붙해서 쓰다가 이 라인 빼먹으면 그대로 버그 나는 겁니다.
    for (let student of students) {
        total += student.score;
    }
    

    답변이 됐을는지요?

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)