자바스크립트 배열 reduce()
예
배열의 모든 숫자 빼기:
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML
= numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
모든 숫자를 반올림하고 합계를 표시합니다.
const numbers = [15.5, 2.3, 1.1, 4.7];
document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
function getSum(total, num) {
return total + Math.round(num);
}
정의 및 사용
이 reduce()
메서드는 배열 요소에 대한 감속기 기능을 실행합니다.
이 reduce()
메서드는 함수의 누적 결과라는 단일 값을 반환합니다.
메서드 는 reduce()
빈 배열 요소에 대해 함수를 실행하지 않습니다.
이 reduce()
방법은 원래 배열을 변경하지 않습니다.
또한보십시오:
통사론
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
매개변수
Parameter | Description | ||||||||
function() | Required. A function to be run for each element in the array. |
||||||||
Reducer function parameters:
| |||||||||
initialValue | Optional. A value to be passed to the function as the initial value. |
반환 값
콜백 함수의 마지막 호출에서 누적된 결과입니다. |
브라우저 지원
reduce()
ECMAScript5(ES5) 기능입니다.
모든 브라우저에서 완전히 지원되는 ES5(JavaScript 2009):
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |