該循環假設我將數組存儲在對象Map中,並顯示出戶外是最有利可圖的部門。在顯示室外變量時遇到問題
我想運行一個遍歷數組的循環,我只是無法在地圖中再次訪問這些數據,並且得到部門最高的利潤(銷售額)。
E.g結合所有的戶外銷售,硬件和木工給你的總和和console.log最高的「室外」。
var salesData = [{
department: 'hardware',
sales: 4500,
day: 'Monday'
}, {
department: 'outdoor',
sales: 1500,
day: 'Monday'
}, {
department: 'carpentry',
sales: 5500,
day: 'Monday'
}, {
department: 'hardware',
sales: 7500,
day: 'Tuesday'
}, {
department: 'outdoor',
sales: 2505,
day: 'Tuesday'
}, {
department: 'carpentry',
sales: 1540,
day: 'Tuesday'
}, {
department: 'hardware',
sales: 1500,
day: 'Wednesday'
}, {
department: 'outdoor',
sales: 8507,
day: 'Wednesday'
}, {
department: 'carpentry',
sales: 8009,
day: 'Wednesday'
}, {
department: 'hardware',
sales: 12000,
day: 'Thursday'
}, {
department: 'outdoor',
sales: 18007,
day: 'Thursday'
}, {
department: 'carpentry',
sales: 6109,
day: 'Thursday'
}, {
department: 'hardware',
sales: 7005,
day: 'Friday'
}, {
department: 'outdoor',
sales: 12006,
day: 'Friday'
}, {
department: 'carpentry',
sales: 16109,
day: 'Friday'
}];
var departmentMap = {};
var high = "";
function mostProfitableDepartment(salesList) {
for (var i = 0; i < salesList.length; i++) {
var currentDep = salesList[i];
if (departmentMap[currentDep] === undefined) {
departmentMap[currentDep] = 0;
}
departmentMap[currentDep] = departmentMap[currentDep] + 1
}
console.log(departmentMap);
}
mostProfitableDepartment(salesData);
for (var depHigh in departmentMap) {
if (departmentMap[depHigh] > high) {
high = departmentMap[depHigh]
}
}
console.log(high);
不完全是,但我確實有做如上指示。我無法得到正確的。 @Endless – Duvall912
Sry,誤解了你的問題,更新了答案 – Endless
我實際上並不瞭解代碼,請你澄清一下,而不使用reduce函數。 @Endless – Duvall912