3

So I have tried this example from W3Schools and I get it.

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();

The "+1" gets you tomorrows date, but what happens when you reach the end of the loop? Say today is Friday and I want to get three days out and Monday comes back as "undefined" because it is past the loop.

Is there any way to start the loop over? From what I've seen, continue/break doesn't work.

Any better suggestions on how to get today's date and the next few so that a loop doesn't break?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Ben Thompson
  • 37
  • 1
  • 6
  • 1
    `getDay` as its name suggest is a getter function and does not takes any arguments. So you are always getting same day irrespective of `i` – Rajesh Dec 22 '17 at 05:44
  • So you want to skip `n` days or just weekends? – dork Dec 22 '17 at 05:46
  • 2
    Possible duplicate of [How to access array in circular manner in javascript](https://stackoverflow.com/questions/17483149/how-to-access-array-in-circular-manner-in-javascript) – 31piy Dec 22 '17 at 05:46
  • Use reminder: `return week[(day.getDay(i) + 1) % 7]` – Nir Alfasi Dec 22 '17 at 05:47

3 Answers3

3

i will not change the day because .getDay() does not process any arguments. Use the modulus operator % to wrap around the 7 days of the week. Run the snippet below to see that it works.

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();
JMA
  • 1,781
  • 9
  • 18
1

I found this to be the best way to create each day of the week in a loop:

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();
Bert W
  • 546
  • 5
  • 11
0

Use '%' operator.

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

}
Brijesh
  • 148
  • 2
  • 16