Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 数组累加

作者:殇丶離別   发布日期:2025-06-24   浏览:64

// 使用 reduce 方法对数组进行累加

const numbers = [1, 2, 3, 4, 5];

// reduce 方法接收一个回调函数,该回调函数有两个参数:累加器 (accumulator) 和当前值 (currentValue)
const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
}, 0); // 初始值为 0

console.log(sum); // 输出: 15

解释说明:

  • numbers 是一个包含数字的数组。
  • reduce 方法用于对数组中的每个元素执行一个 reducer 函数(由您提供),将其结果汇总为单个输出值。
  • accumulator 是累加器,保存了上一次调用回调时返回的值,或者初始值(如果提供了)。
  • currentValue 是当前处理的数组元素。
  • 最后,sum 变量存储了累加的结果。

上一篇:js 数据排序

下一篇:js 最大值

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站