JavaScript中的reduce方法執(zhí)行過(guò)程、使用場(chǎng)景及進(jìn)階用法
1. 什么是reduce
reduce
方法是 JavaScript 中數(shù)組的重要方法之一,用于對(duì)數(shù)組中的元素進(jìn)行累積計(jì)算。它接收一個(gè)回調(diào)函數(shù)作為參數(shù),并返回一個(gè)最終計(jì)算結(jié)果。reduce
在許多場(chǎng)景下都非常有用,比如求和、數(shù)組扁平化、對(duì)象計(jì)數(shù)、數(shù)據(jù)轉(zhuǎn)換等。
2. reduce語(yǔ)法
2.1 語(yǔ)法
arr.reduce(callback, initialValue)
2.2 參數(shù)說(shuō)明
callback(accumulator, currentValue, currentIndex, array)
:回調(diào)函數(shù),接受四個(gè)參數(shù):accumulator
:上一次callback
執(zhí)行后的返回值currentValue
:當(dāng)前值currentIndex
:當(dāng)前元素在數(shù)組中的索引array
:原數(shù)組(正在遍歷的數(shù)組)
initialValue
(可選):累加器的初始值- 如果提供,則accumulator從initialValue開始
- 如果沒(méi)有提供,則取數(shù)組的第一個(gè)元素
3. reduce執(zhí)行過(guò)程
3.1 執(zhí)行過(guò)程
reduce
方法會(huì)遍歷數(shù)組的每個(gè)元素,并對(duì)其應(yīng)用回調(diào)函數(shù)。其執(zhí)行流程如下:
- 初始化
accumulator
:如果提供了initialValue
,則accumulator
取initialValue
,否則取數(shù)組的第一個(gè)元素,并跳過(guò)該元素。 - 遍歷數(shù)組:從索引 0(如果有
initialValue
)或 1(如果沒(méi)有initialValue
)開始,依次執(zhí)行 callback,并更新accumulator
。 - 返回最終的
accumulator
值。
3.2 示例
const numbers = [1, 2, 3, 4]; const result = numbers.reduce((acc, cur, index) => { console.log(`累加器: ${acc}, 當(dāng)前值: ${cur}, 索引: ${index}`); return acc + cur; }, 0); console.log('最終結(jié)果:', result);
執(zhí)行結(jié)果如下:
累加器: 0, 當(dāng)前值: 1, 索引: 0
累加器: 1, 當(dāng)前值: 2, 索引: 1
累加器: 3, 當(dāng)前值: 3, 索引: 2
累加器: 6, 當(dāng)前值: 4, 索引: 3
最終結(jié)果: 10
4. reduce使用場(chǎng)景
4.1 數(shù)組求和
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((acc, cur) => acc + cur, 0); console.log(sum); // 輸出 15
4.2 統(tǒng)計(jì)數(shù)組中元素出現(xiàn)的次數(shù)
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); console.log(count); // { apple: 3, banana: 2, orange: 1 }
4.3 計(jì)算數(shù)組中對(duì)象的某個(gè)屬性總和
const products = [ { name: 'Laptop', price: 1000 }, { name: 'Phone', price: 500 }, { name: 'Tablet', price: 300 } ]; const totalPrice = products.reduce((acc, product) => acc + product.price, 0); console.log(totalPrice); // 輸出 1800
5. reduce進(jìn)階用法
5.1 按屬性分組數(shù)據(jù)
const people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'David', age: 30 } ]; const groupedByAge = people.reduce((acc, person) => { (acc[person.age] = acc[person.age] || []).push(person); return acc; }, {}); console.log(groupedByAge); // 輸出: // { // 25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }], // 30: [{ name: 'Bob', age: 30 }, { name: 'David', age: 30 }] // }
5.2 計(jì)算嵌套對(duì)象的總和
const orders = [ { customer: 'Alice', total: 50 }, { customer: 'Bob', total: 30 }, { customer: 'Alice', total: 20 } ]; const customerTotals = orders.reduce((acc, order) => { acc[order.customer] = (acc[order.customer] || 0) + order.total; return acc; }, {}); console.log(customerTotals); // 輸出:{ Alice: 70, Bob: 30 }
5.3 組合多個(gè)reduce進(jìn)行復(fù)雜計(jì)算
const data = [ { category: 'A', value: 10 }, { category: 'B', value: 20 }, { category: 'A', value: 15 }, { category: 'B', value: 25 } ]; const aggregatedData = data.reduce((acc, item) => { acc[item.category] = (acc[item.category] || []).concat(item.value); return acc; }, {}); const summedData = Object.keys(aggregatedData).reduce((acc, key) => { acc[key] = aggregatedData[key].reduce((sum, num) => sum + num, 0); return acc; }, {}); console.log(summedData); // 輸出:{ A: 25, B: 45 }
6. 手寫reduce實(shí)現(xiàn)
Array.prototype.myReduce = function(callback,initialValue){ const arr = this; // 獲取調(diào)用reduce的數(shù)組 if(typeof callback !== "function"){ // 驗(yàn)證回調(diào)函數(shù)是否傳入 throw new TypeError(`${callback} is not a function`); } let accumulator; // 累加器 let startIndex; // 數(shù)組遍歷起始位置 if(initialValue!==undefined){ // 判斷是否傳遞了初始值 accumulator = initialValue; startIndex = 0; }else{ // 如果沒(méi)有提供初始值,則將第一個(gè)數(shù)組元素作為累加器的初始值 if(arr.length===0){ throw new TypeError(`Reduce of empty array with on initial value`); } accumulator = arr[0]; startIndex = 1; } // 遍歷數(shù)組并應(yīng)用回調(diào)函數(shù) for(let i=startIndex;i<arr.length;i++){ accumulator = callback(accumulator,arr[i],i,arr); } // 返回累加結(jié)果 return accumulator } const numbers = [1,2,3,4,5]; const sum = numbers.myReduce((acc,curr)=>acc+curr,0) // 15 const product = numbers.myReduce((acc,curr)=>acc*curr) // 120
總結(jié)
到此這篇關(guān)于JavaScript中的reduce方法執(zhí)行過(guò)程、使用場(chǎng)景及進(jìn)階用法的文章就介紹到這了,更多相關(guān)JS中reduce方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript事件函數(shù)中獲得事件源的兩種不錯(cuò)方法
許多情況我們需要獲得事件源對(duì)象來(lái)對(duì)其屬性進(jìn)行更改,在事件響應(yīng)函數(shù)中獲得事件源的方法有如下兩種2014-03-03在layui.use 中自定義 function 的正確方法
今天小編就為大家分享一篇在layui.use 中自定義 function 的正確方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-09-09Axios+Spring?Boot實(shí)現(xiàn)文件上傳和下載
這篇文章主要為大家詳細(xì)介紹了Axios+Spring?Boot實(shí)現(xiàn)文件上傳和下載,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08javascript 學(xué)習(xí)筆記(onchange等)
javascript 學(xué)習(xí)筆記,一些簡(jiǎn)單的小技巧,學(xué)習(xí)js的朋友可以看下。2010-11-11JavaScript數(shù)據(jù)分析之交集,并集,對(duì)稱差集
這篇文章主要介紹了JavaScript數(shù)據(jù)分析之交集,并集,對(duì)稱差集,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-07-07千萬(wàn)不要錯(cuò)過(guò)的JavaScript高效對(duì)比數(shù)組差異方法
前端開發(fā)中,我們通常需要對(duì)比兩個(gè)數(shù)組對(duì)象的差異。這其中有很多種方法,但是有些方法會(huì)帶來(lái)一些問(wèn)題,所以本文為大家準(zhǔn)備了一個(gè)高效方法,需要的可以參考一下2023-05-05HTML+CSS+JavaScript實(shí)現(xiàn)簡(jiǎn)單日歷效果
這篇文章主要為大家詳細(xì)介紹了HTML+CSS+JavaScript實(shí)現(xiàn)簡(jiǎn)單日歷效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07基于input框覆蓋掉數(shù)字英文的實(shí)例講解
下面小編就為大家?guī)?lái)一篇基于input框覆蓋掉數(shù)字英文的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07