JavaScript中的reduce方法執(zhí)行過程、使用場景及進階用法
1. 什么是reduce
reduce 方法是 JavaScript 中數組的重要方法之一,用于對數組中的元素進行累積計算。它接收一個回調函數作為參數,并返回一個最終計算結果。reduce 在許多場景下都非常有用,比如求和、數組扁平化、對象計數、數據轉換等。
2. reduce語法
2.1 語法
arr.reduce(callback, initialValue)
2.2 參數說明
callback(accumulator, currentValue, currentIndex, array):回調函數,接受四個參數:accumulator:上一次callback執(zhí)行后的返回值currentValue:當前值currentIndex:當前元素在數組中的索引array:原數組(正在遍歷的數組)
initialValue(可選):累加器的初始值- 如果提供,則accumulator從initialValue開始
- 如果沒有提供,則取數組的第一個元素
3. reduce執(zhí)行過程
3.1 執(zhí)行過程
reduce 方法會遍歷數組的每個元素,并對其應用回調函數。其執(zhí)行流程如下:
- 初始化
accumulator:如果提供了initialValue,則accumulator取initialValue,否則取數組的第一個元素,并跳過該元素。 - 遍歷數組:從索引 0(如果有
initialValue)或 1(如果沒有initialValue)開始,依次執(zhí)行 callback,并更新accumulator。 - 返回最終的
accumulator值。
3.2 示例
const numbers = [1, 2, 3, 4];
const result = numbers.reduce((acc, cur, index) => {
console.log(`累加器: ${acc}, 當前值: ${cur}, 索引: ${index}`);
return acc + cur;
}, 0);
console.log('最終結果:', result);
執(zhí)行結果如下:
累加器: 0, 當前值: 1, 索引: 0
累加器: 1, 當前值: 2, 索引: 1
累加器: 3, 當前值: 3, 索引: 2
累加器: 6, 當前值: 4, 索引: 3
最終結果: 10
4. reduce使用場景
4.1 數組求和
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((acc, cur) => acc + cur, 0); console.log(sum); // 輸出 15
4.2 統計數組中元素出現的次數
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 計算數組中對象的某個屬性總和
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進階用法
5.1 按屬性分組數據
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 計算嵌套對象的總和
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 組合多個reduce進行復雜計算
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實現
Array.prototype.myReduce = function(callback,initialValue){
const arr = this; // 獲取調用reduce的數組
if(typeof callback !== "function"){ // 驗證回調函數是否傳入
throw new TypeError(`${callback} is not a function`);
}
let accumulator; // 累加器
let startIndex; // 數組遍歷起始位置
if(initialValue!==undefined){ // 判斷是否傳遞了初始值
accumulator = initialValue;
startIndex = 0;
}else{
// 如果沒有提供初始值,則將第一個數組元素作為累加器的初始值
if(arr.length===0){
throw new TypeError(`Reduce of empty array with on initial value`);
}
accumulator = arr[0];
startIndex = 1;
}
// 遍歷數組并應用回調函數
for(let i=startIndex;i<arr.length;i++){
accumulator = callback(accumulator,arr[i],i,arr);
}
// 返回累加結果
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總結
到此這篇關于JavaScript中的reduce方法執(zhí)行過程、使用場景及進階用法的文章就介紹到這了,更多相關JS中reduce方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
在layui.use 中自定義 function 的正確方法
今天小編就為大家分享一篇在layui.use 中自定義 function 的正確方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-09-09

