在JavaScript中,数组数组求和是求和常见的操作之一,下面介绍五(wu)种常用的常用方法来实现数组求和:(图片来源网络,侵删)
1、数组(zu)使用reduce()方法

const array = [1,求和 2, 3, 4, 5];const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(sum); // 输出:15
reduce()方法(fa)接受一个回调函数作为参数(shu),该回调函数有两个参数:累加器(accumulator)和当前值(currentValue),常用初始值为0,数组每(mei)次迭代时将当前值与累加器的求和值相加,并(bing)将(jiang)结果(guo)作为新的常(chang)用累加器值传递给下一次迭代,最终的数组累加(jia)器值即为数组(zu)的和(he)。

2、求和使(shi)用for...of循环

const array = [1,常用 2, 3, 4, 5];let sum = 0;for (const value of array) { sum += value;}console.log(sum); // 输出:15使(shi)用for...of循环遍历数组(zu)中的每个元素,并将其累加到变量sum中,数组最后输出sum的求和值即可得到数组的和。
3、常用使用Array.prototype.forEach()方法
const array = [1, 2, 3, 4, 5];let sum = 0;array.forEach(value => sum += value);console.log(sum); // 输出:15
使用forEach()方法遍历数组中(zhong)的每个元素,并将其(qi)累加到变量sum中,最后输出sum的值即可得到数组的和。
4、使用(yong)扩展运算符(Spread operator)和Array.prototype.reduce()方法
const array = [1, 2, 3, 4, 5];const sum = [...array].reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(sum); // 输出:15
使用扩展运算符将数组转换为一个新数组,然后对该新数组使用(yong)reduce()方法进行求和(he)操作,最终的累加器值即为数组的和。
const array = [1, 2, 3, 4, 5];const sum = ([...array]).reduce((accumulator, currentValue) => accumulator + currentValue, 0);console.log(sum); // 输出:15
使用展开运算符将数组转换为一个新数组,并使用箭头函数作为(wei)回调函数传递给reduce()方法进行(xing)求和操作,最终的累加器值即为数组的和。
(作者:代运营)