gpt4 book ai didi

javascript - 2D Array 或 Map 以在几天内针对工作日和插槽存储值

转载 作者:行者123 更新时间:2023-11-29 15:24:41 26 4
gpt4 key购买 nike

我想增加一周中的几天和每天的时间段的值,即早上、下午、晚上和晚上,因为我迭代了一个集合,在那里我得到了时间,然后评估时间在哪个时间段。我需要能够在前端迭代最终结果,但想要一个比我目前所代表的更好的解决方案,但总计数组。有人建议我使用 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 Array 或 Map 以在几天内针对工作日和插槽存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40530250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com