gpt4 book ai didi

javascript - 从日期编号创建一系列日期名称?

转载 作者:行者123 更新时间:2023-11-29 16:02:38 25 4
gpt4 key购买 nike

我有一组天数,我想将其转换为更漂亮的字符串格式。相应的日期名称必须显示为一个范围。

这是一个例子:

// 0 is Sunday, 6 is Saturday

days = [0,1,2,4,5];
// Should be ["Sunday-Tuesday", "Thursday-Friday"]

days = [0,1,3,5,6]
// Should be ["Friday-Monday", "Wednesday"]
// note that this wraps around!!

我已经尝试过并且有些成功,但它并没有环绕。它也很丑陋,imo。

let result = [];
let build = "";
let previous = -10;
let days = [0,1,3,5,6];

for(let i=0;i < days.length; i++) {
let d = parseInt(days[i]);

if (d !== previous+1 && i > 0) {
build = build.slice(1).split(",");
if (build.length == 1)
build = build[0];
else if (build.length > 0) {
build = build[0] + "-" + build[build.length-1];
}
result.push(build);
build = "";
}

build = build + "," + getDayName(d);

if (i === days.length-1) {
build = build.slice(1).split(",");
if (build.length == 1)
build = build[0];
else if (build.length > 0) {
build = build[0] + "-" + build[build.length-1];
}
result.push(build);
}
previous = d;
}

这只会打印出 Array [ "Sunday-Monday", "Wednesday", "Friday-Saturday"]

我怎样才能让每一天都过去?有没有更简洁的方法来做到这一点?

最佳答案

您可以将第一个连续日期连接到数组的末尾,这样当我们运行算法对它们进行分组时,换行会自动处理。

let names = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(',');
let i = 0;
while (days[i]+1 == days[i+1]) i++;
days = days.concat(days.splice(0, i+1));
let res = [];
let s = days[0];
for (i = 0; i < days.length-1; i++){
if ((days[i]+1)%7 != days[i+1]){
let f = days[i];
res.push(s == f ? names[s] : names[s]+'-'+names[f]);
s = days[i+1];
}
}
f = days[days.length-1];
res.push(s == f ? names[s] : names[s]+'-'+names[f]);
res.unshift(res.pop());

关于javascript - 从日期编号创建一系列日期名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415088/

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