views:

202

answers:

2

Hi

I have some code which builds an array of date ranges. I then call a function (from the jquery UI datepicker), passing it a date, and compare that date with dates in the array. I'm doing it this way because the dates are stored in a cms and this is the only way I can output them.

Unfortunately my code only checks the first date range in the array - and I can't figure out why! I think it's probably something simple (/stupid!) - if anyone can shed some light on it I'd be extremely grateful!

The code is below - the june-september range (ps1-pe1) works fine, the december to jan is totally ignored...

<script type="text/javascript" language="javascript"> 

var ps1 = new Date(2010, 06-1, 18); // range1 start
var pe1 = new Date(2010, 09-1, 03); // range1 end
var ps2 = new Date(2010, 12-1, 20); // range2 start
var pe2 = new Date(2011, 01-1, 02); // range2 end

var peakStart = new Array(ps1,ps2);
var peakEnd = new Array(pe1,pe2);
function checkDay(date) {
    var day = date.getDay();
    for (var i=0; i<peakStart.length; i++) {
        if ((date > peakStart[i]) && (date < peakEnd[i])) {
            return [(day == 5), ''];
        } else {
            return [(day == 1 || day == 5), ''];
        }
    }
}
</script>
+1  A: 

You always call return in the first iteration of for loop.

jholster
Sorry Yaggo, I don't quite understand - should I write a variable inside the loop and then return it outside?
PaulB
OK, I've also tried this (modified function, other vars/arrays remain), which makes the second range work and ignores the first! function checkDay(date, season) { var day = date.getDay(); var period = ""; for (var i=0; i<peakStart.length; i++) { if ((date > peakStart[i]) } else { period = "non_peak"; } } if (period=="peak") { return [(day == 5), ''] } else { return [(day == 1 || day == 5), '']}; }
PaulB
Sorry, can't format the comment :-s
PaulB
In the modified function, the second iteration of the loop clobbers whatever value went into 'period' during the first iteration. Which is why it apparently ignores the first range.
brainjam
+1  A: 

Yaggo is quite right, but apparently too terse.

You want to move the second return statement outside of the loop.

function checkDay(date) {
    var day = date.getDay();
    for (var i=0; i<peakStart.length; i++) {
        if ((date > peakStart[i]) && (date < peakEnd[i])) {
            return [(day == 5), ''];
        }
    }
    // it's not during a peak period
    return [(day == 1 || day == 5), ''];
}
brainjam
Many thanks brainjam and Yaggo! This solution worked and also showed me that I should take a break once in a while as now it's obvious :) Thanks again guys
PaulB