0

我想在我的网站上的一些 div 中放置 5 个即将到来的日期名称。我已经为日期名称创建了数组,然后我从中调用值并添加天数。该方法仅适用于前一天,然后数组结束,从第 2 天到第 5 天它回显“未定义”。

请帮忙?

var weekday=new Array(7);
weekday[0]="Nedelja";
weekday[1]="Ponedeljek";
weekday[2]="Torek";
weekday[3]="Sreda";
weekday[4]="Četrtek";
weekday[5]="Petek";
weekday[6]="Sobota";
var dan = weekday[today.getDay()];

var dan_1 = weekday[today.getDay()+1];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[today.getDay()+2];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[today.getDay()+3];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[today.getDay()+4];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[today.getDay()+5];
document.getElementById("day5").innerHTML = dan_5;

谢谢你们!

4

3 回答 3

2

好吧,您需要 % 和 7(一周中的天数)

var weekday=new Array(7);
weekday[0]="Nedelja";
weekday[1]="Ponedeljek";
weekday[2]="Torek";
weekday[3]="Sreda";
weekday[4]="Četrtek";
weekday[5]="Petek";
weekday[6]="Sobota";
var dan = weekday[today.getDay()%7];

var dan_1 = weekday[(today.getDay()+1)%7];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[(today.getDay()+2)%7];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[(today.getDay()+3)%7];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[(today.getDay()+4)%7];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[(today.getDay()+5)%7];
document.getElementById("day5").innerHTML = dan_5;

例如:如果today.getDay()返回 5,则接下来的 5 天是 10,这在您的数组中不存在。当你 % 7 时,你会得到 3(下周)

于 2013-05-24T13:20:36.970 回答
1

%您可以在数组访问中添加模运算以防止溢出并在开始时重新启动:

// ...
var dan_1 = weekday[(today.getDay()+1)%7];
document.getElementById("day1").innerHTML = dan_1;
var dan_2 = weekday[(today.getDay()+2)%7];
document.getElementById("day2").innerHTML = dan_2;
var dan_3 = weekday[(today.getDay()+3)%7];
document.getElementById("day3").innerHTML = dan_3;
var dan_4 = weekday[(today.getDay()+4)%7];
document.getElementById("day4").innerHTML = dan_4;
var dan_5 = weekday[(today.getDay()+5)%7];
document.getElementById("day5").innerHTML = dan_5;

示例小提琴

于 2013-05-24T13:21:23.310 回答
0

你的问题是以合乎逻辑的方式推进这一天。这是通过添加到当前日期并%从除以 7 中选择余数(模, )来实现的。请参见(dan + i) % 7下面代码中的部分。

我将使用Khanh TO 的答案中已经固定的代码,并以更简洁的方式编写它。现在你的代码有点重复,这可以通过使用数组文字和循环来帮助。

var today = new Date();
var weekday = ["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"];
var dan = today.getDay();
for (var i = 1; i <= 5; i++) {
    var elem = document.getElementById("day" + i);
    elem.innerHTML = weekday[(dan + i) % 7];
}

我相信看到更优雅的风格对你是有好处的。

于 2014-10-28T18:33:08.627 回答