// 使用 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
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站