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

js .reduce

作者:狂拽今生   发布日期:2026-07-09   浏览:33

// 使用 reduce 方法计算数组元素的总和
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);

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

// 解释:
// reduce 方法会遍历数组中的每个元素,并将一个累积值 (accumulator) 和当前元素 (currentValue) 传递给回调函数。
// 在这个例子中,我们从 0 开始累加数组中的所有数字,最终得到总和 15。
// 使用 reduce 方法将数组转换为对象
const array = [['apple', 1], ['banana', 2], ['orange', 4]];

const object = array.reduce((accumulator, [key, value]) => {
  accumulator[key] = value;
  return accumulator;
}, {});

console.log(object); // 输出: { apple: 1, banana: 2, orange: 4 }

// 解释:
// 这里我们将一个二维数组转换成了一个对象。reduce 方法遍历数组的每一项,并将每一项的键值对添加到累积对象中。

上一篇:js 滚动到指定位置

下一篇:js math.sqrt

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站