views:

41

answers:

3

Hey, Easy question, my brain is empty today.. I have a array with month(1-12) and a given month.

var cMonate = new Array("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli",
                            "August", "September", "Oktober", "November", "Dezember");

My given month:

var Month = currentMonth.getMonth(); 

Month is 8. Now I will read the last 3 month and the coming month.

Easy sample: may june july august september october november

How can I find out ?

+2  A: 
for(var m = Month - 3; m <= Month + 3) {
  var usedMonth = (m < 1 ? m + 12 : (m > 12 ? m - 12 : m));
  // use 'usedMonth' here for whatever...e.g.:
  console.log(cMonate[usedMonth-1]);
}
sje397
Hey, whats console.log(cMonate[usedMonth-1]); ? Can you explain it for me ?
Patrik
@Patrik: console.log just prints a string (in FF if you install firebug, or in Chrome dev tools). You have an array (which in javascript are indexed starting at 0) of month names `cMonate`. Because the `cMonate` indexes start at 0 and `usedMonth` starts at 1, you need to subtract one. So, this just prints out the months, as per your 'sample output'.
sje397
+1  A: 

Are you aware of datejs?

kgiannakakis
A: 

Regard your months as an infinite series, starting from -infinity, going to -3, -2, -1, 0, 1, 2, ..., 12, 13, 14, ...

Then it's easy:

for( var infindex = monthindex-3; infindex < month+4; ++infindex ) {
   return month( infindex );
}

Then you can create a mapping from the infinite index to the ever-recurring sequence:

function month( infiniteindex ) {
  var index = infinteindex % 12; // since every 12 months, the same month occurs.
  // EDIT --- javascript allows negative result for modulo
  if( index < 0 ) index = index+12;
  return cMonate[index];
}
xtofl
var cMonate = new Array("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"); for (var infindex = Monat - 3; infindex < Monat + 4; ++infindex) { var index = infindex % 12; alert(cMonate[index]); }
Patrik
This is wrong: if `infindex` is -2, -2 % 12 == -2, and `cMonat[-2]` is `undefined`.
sje397
@sje397: darn - indeed: ECMAScript standard dictates that `abs(k) < abs(y) in k=x%y`... We can fix that by adding `y` again to the negative result.
xtofl