reduce 函数用于累积操作,得到单一值:接收数组、回调函数和初始值(可选)。回调函数处理累积器(存储累积结果)和当前元素。初始值是累积器的起始值,默认为数组第一个元素。用例包括求和、求平均值、连接数组、过滤和分组。

JS 中 reduce 函数的用法
reduce 函数是 JavaScript 中的一个函数,用于对一个数组中的元素进行累积操作,最终得到一个单一值。它的用法如下:
<code class="javascript">const result = array.reduce(callback, initialValue);</code>
其中:
回调函数
回调函数接收两个参数:
initialValue
initialValue 是累积器的初始值,如果没有指定,则会使用数组的第一个元素作为初始值。
用法
reduce 函数经常用于以下场景:
示例
求和:
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 输出:15</code>
求平均值:
<code class="javascript">const numbers = [1, 2, 3, 4, 5]; const average = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / numbers.length; console.log(average); // 输出:3</code>
连接数组:
<code class="javascript">const names = ['John', 'Mary', 'Bob']; const joinedString = names.reduce((accumulator, currentValue) => accumulator + ', ' + currentValue); console.log(joinedString); // 输出:John, Mary, Bob</code>
过滤数组:
<code class="javascript">const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.reduce((accumulator, currentValue) => {
  if (currentValue % 2 === 0) {
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);
console.log(evenNumbers); // 输出:[2, 4]</code>以上就是js中reduce函数的用法的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号