JavaScript의 reduce() 메서드를 사용하여 배열의 두 값에 대해 동시에 함수를 왼쪽에서 오른쪽으로 적용하여 단일 값으로 줄이십시오.
다음은 매개변수입니다 -
- 콜백 − 배열의 각 값에 대해 실행할 함수입니다.
- 초기값 − 콜백의 첫 번째 호출에 대한 첫 번째 인수로 사용할 개체입니다.
예시
다음 코드를 실행하여 JavaScript에서 reduce() 메서드를 사용하는 방법을 배울 수 있습니다.
<html>
<head>
<title>JavaScript Array reduce Method</title>
</head>
<body>
<script>
if (!Array.prototype.reduce) {
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len == 0 && arguments.length == 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
}
while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
};
}
var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });
document.write("total is : " + total );
</script>
</body>
</html>