所以我尝试过来自W3Schools的this example,我就明白了。
function day() {
var day = new Date();
var week = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
);
for (i = 0; i < week.length; i++) {
console.log(week[day.getDay(i) + 1]);
}
}
day();
“+1”会让你明天约会,但是当你到达循环结束时会发生什么?说今天是星期五,我想要三天出去,周一回来“未定义”,因为它已经过了循环。
有没有办法开始循环?从我所看到的,继续/中断不起作用。
关于如何获得今天的日期和接下来的几个更好的建议,以便循环不会中断?
答案 0 :(得分:1)
我发现这是循环创建一周中每一天的最佳方式:
function days() {
var day = new Date();
var week = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
);
for (i = 0; i < 7; i++) {
console.log(week[(day.getDay() + i) % 7]);
}
}
days();
答案 1 :(得分:0)
使用&#39;%&#39;操作
function day() {
var day = new Date();
var week = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
);
for (i=0; i<week.length; i++) {
var num = (day.getDay(i)+3)%7;
console.log(week[num]);
}
}
答案 2 :(得分:0)
i
不会更改日期,因为.getDay()不会处理任何参数。使用模数运算符%
包围一周中的7天。运行下面的代码段,看它是否有效。
function day() {
var day = new Date();
var week = new Array(
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
);
for (i = 0; i < 14; i++) {
console.log(week[(day.getDay() + 1 + i) % 7]);
}
}
day();
&#13;
答案 3 :(得分:0)