Question

Currently I'm showing various weather parameters in a table and I also want the current day and the six following days to be in the first column.

I started to create the weekdays like this:

// Make variables for every weekday
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 today = d.getDay();

And my table looks like this.

$('#weakly-table').append('<tr><td>Day</td><td>Temperature</td> <td>Description</td> <td> Pressure </td> <td> Humidity </td> <td> Wind speed </td> </tr>') 

    $.each(weaklyWeather.list, function(index, weather) {
    $('#weakly-table').append('<tr><td>' + weekday[today] + '</td><td>' + Math.round(weaklyWeather.list[index].temp.day) + '&#176C  &nbsp</td> <td> <img src="http://openweathermap.org/img/w/'+ weaklyWeather.list[index].weather[0].icon+'"/>' + '</td> <td>' + Math.round(weaklyWeather.list[index].pressure) + ' Pa' + '</td><td>' + Math.round(weaklyWeather.list[index].humidity) + ' %' + '</td><td>' + Math.round(weaklyWeather.list[index].speed) + ' m/s' + '</td></tr>');

Instead of writing weekday[today] in the first column for every row I want it to be weekday[today + 1], weekday[today + 2] and so on but that will just give me the next day on every row.

Any suggestions?

Was it helpful?

Solution

No need to use jQuery if you just want to iterate through an array. A normal JavaScript for loop will do just fine.

for(var i=0;i<weekdays.length;i++){
   console.log(weekdays[i]); //logs the i'th weekday
}

If you want to start at a specific week day you can do

var today = 2; //Tuesday
var numDays = weekday.length;
for(var i=0;i<numDays;i++){
   console.log(weekday[(i+today) % numDays]); 
}

Fiddle

Fiddle starting with today

What we do is use the modulus operator which represents the remainder. If you are unfamiliar with it, think about it like time in a clock. You're wrapping values (days of week) here (like in a clock).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top