"함수 reduce()"의 두 판 사이의 차이

1번째 줄: 1번째 줄:
;reduce
;reduce
==JavaScript==
[[분류: JavaScript]]
{{참고|자바스크립트 배열 reduce()}}
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
</syntaxhighlight>
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(reducer));    // 130 = 100 + 20 + 10
console.log(numbers.reduce(reducer, 5)); // 135 = 5 + 100 + 20 + 10
</syntaxhighlight>
<syntaxhighlight lang='javascript' run>
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10
</syntaxhighlight>


==PHP==
==PHP==

2021년 5월 2일 (일) 15:21 판

reduce

1 JavaScript

const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total + num;
});
console.log( result ); // 130 = 100 + 20 + 10
const numbers = [100, 20, 10];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(numbers.reduce(reducer));    // 130 = 100 + 20 + 10
console.log(numbers.reduce(reducer, 5)); // 135 = 5 + 100 + 20 + 10
const numbers = [100, 20, 10];
const result = numbers.reduce(function(total, num) {
  return total - num;
});
console.log( result ); // 70 = 100 - 20 - 10

2 PHP

$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry += $i;
    return $carry;
});
echo $result; # 14
$a = [2, 3, 4, 5];
$result = array_reduce($a, function($carry, $i) {
    $carry *= $i;
    return $carry;
}, 1);
echo $result; # 120

3 Python

Python 3
from functools import reduce
a = [2, 3, 4, 5]
print( reduce((lambda x, y: x*y), a) ) # 120

4 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}