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

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


咨詢
建站咨詢
