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

js 数组reduce

作者:冷月魄   发布日期:2026-01-27   浏览:98

// 使用 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 开始累加数组中的每个数字,最终得到数组中所有元素的和。

// 使用 reduce 方法将数组中的对象属性值相加
const items = [
    { quantity: 2, price: 20 },
    { quantity: 5, price: 10 },
    { quantity: 1, price: 50 }
];

const total = items.reduce((accumulator, item) => {
    return accumulator + (item.quantity * item.price);
}, 0);

console.log(total); // 输出: 120

// 解释说明:
// 在这个例子中,我们使用 reduce 方法来计算购物车中所有商品的总价。
// 每个商品都有数量 (quantity) 和价格 (price),我们通过累加每个商品的数量乘以价格来得到总价。

上一篇:js 数组函数

下一篇:js 获取本机ip

大家都在看

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 数组对象合并

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

Laravel 中文站