我想在一周中的某几天和每天的时段内增加值,即早上,下午,晚上和晚上,因为我要遍历一个集合并获取时间,然后评估该时间所在的时隙。
我需要能够遍历前端的最终结果,但是想要一个更好的解决方案,该解决方案我目前已代表但总数数组。有人建议我使用 map ,但不确定如何使用 map 来实现。

   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

    }

任何建议将不胜感激。

最佳答案

我设计数据结构的方法之一如下-参见具有输入,输出和总计计算方法的演示:

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;}

关于javascript - 2D数组或映射可针对工作日和几天内的时段存储值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40530250/

10-12 17:45