2016-11-10 22 views
3

我想增加價值的天和星期幾內每天,即上午,下午,晚上和夜間,因爲我迭代了一個集合,我得到然後評估時間是在哪個時隙。 我需要能夠遍歷前端的最終結果,但想要一個更好的解決方案,即我目前代表的一個更好的解決方案,但總計數組。有人建議我使用地圖,但不確定如何使用地圖來實現此功能。二維數組或地圖存儲價值與平日和插槽天

var totals = [ 
    // Tot M T W T F S S 
    [0, 0, 0, 0, 0, 0, 0, 0], // Totals 
    [0, 0, 0, 0, 0, 0, 0, 0], // Morning 
    [0, 0, 0, 0, 0, 0, 0, 0], // Afternoon 
    [0, 0, 0, 0, 0, 0, 0, 0], // Evening 
    [0, 0, 0, 0, 0, 0, 0, 0]  // Night 
]; 



var collectionOfData = entiredataset; 


collectionOfData.forEach(function (item) { 
    var localDate = getLocalDate(item);//gets users local date and determines timeslot id - ie Morning,afternoon, evening, or night 
    var dayOfWeek = localDate.day(); 
    var timeslotId = item.timeslotId; 

    totals[timeslotId][dayOfWeek]++; // Increase sessions per slot and day 
    totals[0][dayOfWeek]++;   // Increase total sessions per day 
    totals[timeslotId][0]++; // Increase total sessions per slot 
    totals[0][0]++;    // Increase total sessions 

    } 

任何建議將不勝感激。

回答

1

一個我將設計的數據結構的一個方法是如下 - 見演示具有輸入,輸出和總的計算方法:

var slots={'Monday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Tuesday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Wednessday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Thursday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Friday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Saturday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},'Sunday':{'Morning':0,'Afernoon':0,'Evening':0,'Night':0},} 
 

 
// input data 
 
function insertSlotFor(day, slot) { 
 
    slots[day][slot]++; 
 
} 
 

 
// output data 
 
function getSlotFor(day, slot) { 
 
    return slots[day][slot]; 
 
} 
 

 
// get total for a day 
 
function totalForDay(day) { 
 
    return Object.keys(slots[day]).reduce(function(prev,curr){ 
 
    return prev + slots[day][curr]; 
 
    },0); 
 
} 
 

 
// get total for a slot 
 
function totalForSlot(slot) { 
 
    return Object.keys(slots).reduce(function(prev,curr){ 
 
    return prev + slots[curr][slot]; 
 
    },0); 
 
} 
 

 
insertSlotFor('Monday', 'Morning'); 
 
insertSlotFor('Monday', 'Night'); 
 
insertSlotFor('Tuesday', 'Morning'); 
 

 
console.log(slots); 
 

 
console.log(totalForDay('Monday')); 
 
console.log(totalForSlot('Morning'));
.as-console-wrapper{top:0;max-height:100%!important;}

0

您需要定義例如DayOfWeek,並且在該對象中具有將執行所有邏輯的方法。這將封裝邏輯並使其更容易管理代碼。然後,您的數組將保存該對象的實例,並且您只需通過其索引(dayOfWeek)引用對象並調用方法來獲取總計。

你的getLocalDate()函數應該做它所說的 - 獲取數據,而不是在項目中設置任何東西(即timeslotId)。這是令人困惑和混合的責任。它可以是DayOfWeek對象的方法,誰的構造函數將獲得一個項目並根據需要返回值。