donaricano-btn

배열의 요소를 모두 더해라 - reduce()/reduceRight()

- reduce() : 누적자 함수를 인자로 받은 다음 배열의 모든 요소를 누적자 함수에 적용

- 문자열 연결도 가능하다

- reduceRight(): 오른쪽 값부터 누적 된다

- reduce(누적자함수)


1. 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function check() {
 
    var nums = [1,3,5];
    var words = ['I ','LIKE ','A ','APPLE'];
 
    var total = nums.reduce(add);
    var sentence = words.reduce(add);
 
    document.getElementById("result").innerHTML = total;
    document.getElementById("result1").innerHTML = sentence;
 
}
 
function add(total, value){
 
    var total = total + value;
    return total;
}

- add()는 누적자 함수 이다

- 9

I LIKE A APPLE

- reduceRight()를 했다면 APPLE A LIKE I 가 됬을 것이다


블로그 이미지

리딩리드

,