西安至成網(wǎng)站建設(shè)公司寧波seo外包代運(yùn)營(yíng)
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開(kāi)始
- 如果沒(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
)開(kāi)始,依次執(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