新聞中心
在JavaScript中,數(shù)組求和是常見(jiàn)的操作之一,下面介紹五種常用的方法來(lái)實(shí)現(xiàn)數(shù)組求和:

成都創(chuàng)新互聯(lián)專注于企業(yè)成都營(yíng)銷網(wǎng)站建設(shè)、網(wǎng)站重做改版、海港網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5場(chǎng)景定制、商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為海港等各大城市提供網(wǎng)站開(kāi)發(fā)制作服務(wù)。
1、使用reduce()方法
const array = [1, 2, 3, 4, 5]; const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 輸出:15
reduce()方法接受一個(gè)回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)有兩個(gè)參數(shù):累加器(accumulator)和當(dāng)前值(currentValue),初始值為0,每次迭代時(shí)將當(dāng)前值與累加器的值相加,并將結(jié)果作為新的累加器值傳遞給下一次迭代,最終的累加器值即為數(shù)組的和。
2、使用for...of循環(huán)
const array = [1, 2, 3, 4, 5];
let sum = 0;
for (const value of array) {
sum += value;
}
console.log(sum); // 輸出:15
使用for...of循環(huán)遍歷數(shù)組中的每個(gè)元素,并將其累加到變量sum中,最后輸出sum的值即可得到數(shù)組的和。
3、使用Array.prototype.forEach()方法
const array = [1, 2, 3, 4, 5]; let sum = 0; array.forEach(value => sum += value); console.log(sum); // 輸出:15
使用forEach()方法遍歷數(shù)組中的每個(gè)元素,并將其累加到變量sum中,最后輸出sum的值即可得到數(shù)組的和。
4、使用擴(kuò)展運(yùn)算符(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
使用擴(kuò)展運(yùn)算符將數(shù)組轉(zhuǎn)換為一個(gè)新數(shù)組,然后對(duì)該新數(shù)組使用reduce()方法進(jìn)行求和操作,最終的累加器值即為數(shù)組的和。
5、使用箭頭函數(shù)和展開(kāi)運(yùn)算符(Spread operator)
const array = [1, 2, 3, 4, 5]; const sum = ([...array]).reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 輸出:15
使用展開(kāi)運(yùn)算符將數(shù)組轉(zhuǎn)換為一個(gè)新數(shù)組,并使用箭頭函數(shù)作為回調(diào)函數(shù)傳遞給reduce()方法進(jìn)行求和操作,最終的累加器值即為數(shù)組的和。
網(wǎng)站標(biāo)題:JavaScript數(shù)組求和的5種常用方法
分享地址:http://m.fisionsoft.com.cn/article/ccehphi.html


咨詢
建站咨詢
