B. Fett
B. Fett

Reputation: 13

Javascript - Cannot display more than 4 days of the week?

I'm trying to show a schedule that lists the remaining days of the week, but it doesn't work if i use getDay() more than 4 times in the function, which is necessary for getting the days. I made a small sample code to show what i mean. Uncomment the line and it should not work.

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
    alert("hit");
    var d = new Date();
    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";

    var a = weekday[d.getDay()];
    var b = weekday[(d.getDay() + 1) % 7];
    var c = weekday[(d.getDay() + 2) % 7];
    var d = weekday[(d.getDay() + 3) % 7];
    //var e = weekday[(d.getDay() + 4) % 7];

    document.getElementById("day1").innerHTML = a;
}
</script>
</head>
<body onload="myFunction()">
<h1 id="day1">Test</h1>
</body>
</html>

Upvotes: 0

Views: 34

Answers (1)

Paul
Paul

Reputation: 36339

You reassign the variable d.

var d = weekday[(d.getDay() + 3) % 7];

However, it seems unnecessary to solve this problem when you can just call d.getDay() one time, store that in a variable and then do your other manipulations from that. Eg:

function myFunction() {
    alert("hit");
    var d = new Date();
    var day = d.getDay(); 

    var weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

    var a = weekday[day];
    var b = weekday[(day + 1) % 7];
    var c = weekday[(day + 2) % 7];
    var d = weekday[(day + 3) % 7];
    var e = weekday[(day + 4) % 7];

    document.getElementById("day1").innerHTML = a;
}

Upvotes: 1

Related Questions