728x90
반응형
reduce(), reduceRight()
2. reduce() / reduceRight()
reduce()메서드와 reduceRight()메서드는 배열 요소를 하나로 정리하여 결과값을 반환합니다. 둘의 차이점은 reduceRight() 메서드가 배열의 끝에서부터 시작합니다. 배열이 숫자라면 합을 구할 수 있고, 문자라면 결합하여 반환합니다.
번호 | 기본값 | 메서드 | 리턴값 |
---|---|---|---|
js
//01. reduce
const arrNum1 = [100, 200, 300, 400, 500];
const arrReduce1 = arrNum1.reduce(element => element);
document.querySelector(".sample07_N1").innerHTML = "1";
document.querySelector(".sample07_Q1").innerHTML = "[100, 200, 300, 400, 500]";
document.querySelector(".sample07_M1").innerHTML = "arrNum1.reduce(element => element)";
document.querySelector(".sample07_P1").innerHTML = arrReduce1;
const arrNum2 = [100, 200, 300, 400, 500];
const arrReduce2 = arrNum2.reduce((p, c) => p + c);
document.querySelector(".sample07_N2").innerHTML = "2";
document.querySelector(".sample07_Q2").innerHTML = "[100, 200, 300, 400, 500]";
document.querySelector(".sample07_M2").innerHTML = "arrNum2.reduce((p, c) => p + c)";
document.querySelector(".sample07_P2").innerHTML = arrReduce2;
const arrNum3 = [100, 200, 300, 400, 500];
let sum = 0;
for (let i = 0; i < arrNum3.length; i++) {
sum += arrNum3[i];
}
document.querySelector(".sample07_N3").innerHTML = "3";
document.querySelector(".sample07_Q3").innerHTML = "[100, 200, 300, 400, 500]";
document.querySelector(".sample07_M3").innerHTML = "for()";
document.querySelector(".sample07_P3").innerHTML = sum;
const arrNum4 = [[100, 200], [300, 400]];
const arrReduce4 = arrNum4.reduce((p, c) => p.concat(c));
document.querySelector(".sample07_N4").innerHTML = "4";
document.querySelector(".sample07_Q4").innerHTML = "[[100,200], [300, 400]]";
document.querySelector(".sample07_M4").innerHTML = "reduce((p,c) => p.concat(c))";
document.querySelector(".sample07_P4").innerHTML = arrReduce4;
//02. reduceRight
const arrNum5 = ["javascript", "react", "vue"];
const arrReduce5 = arrNum5.reduceRight((p, c) => p + c);
document.querySelector(".sample07_N5").innerHTML = "5";
document.querySelector(".sample07_Q5").innerHTML = "['javascript', 'react', 'vue']";
document.querySelector(".sample07_M5").innerHTML = "reduceRight((p,c) => p+c)";
document.querySelector(".sample07_P5").innerHTML = arrReduce5;
728x90
반응형
'javascript' 카테고리의 다른 글
JavaScript indexOf(), lastIndexOf(), includes() (2) | 2022.09.27 |
---|---|
JavaScript slice(), splice() (2) | 2022.09.27 |
JavaScript concat() (2) | 2022.09.27 |
JavaScript reverse(), sort() (2) | 2022.09.27 |
JavaScript unshift(), shift() (2) | 2022.09.27 |