John_911
John_911

Reputation: 1170

Why is this .push() not working as expected?

var rangesliderfilter = function () {
    var low = parseInt(jQuery('#min-value-span').text());
    var high = parseInt(jQuery('#max-value-span').text());
    var BreakfastDR = [];
    var LunchDR = [];
    var DinnerDR = [];
    var SnacksDR = [];
    while (low <= high) {
        BreakfastDR.push('.' + low++ +'.breakfast');
        LunchDR.push('.' + low++ +'.lunch');
        DinnerDR.push('.' + low++ +'.dinner');
        SnacksDR.push('.' + low++ +'.snacks');
        }

    jQuery('.rangecheck').attr('value', BreakfastDR);
}

This is adding the value in intervals of 4. So if low is 0 and high is 16 the string added is: .0.breakfast,.4.breakfast,.8.breakfast,.12.breakfast

It should be doing every number this way not just in intervals of 4. .0.breakfast,.1.breakfast,.2.breakfast,etc

anyone see an obvious reason why? Should I not be pushing into different vars in the same while function??

Upvotes: 0

Views: 84

Answers (2)

paxdiablo
paxdiablo

Reputation: 881623

It's because you're incrementing low four times with the following code, once after each meal type:

BreakfastDR.push('.' + low++ +'.breakfast');  // Use 0, set to 1.
LunchDR.push('.' + low++ +'.lunch');          // Use 1, set to 2.
DinnerDR.push('.' + low++ +'.dinner');        // Use 2, set to 3.
SnacksDR.push('.' + low++ +'.snacks');        // Use 3, set to 4.

So breakfast will get 0, lunch will get 1 and so on. The next breakfast after the initial one will get 4. You'll end up with:

breakfast   0,  4,  8, 12, 16, ...
lunch       1,  5,  9, 13, 17, ...
dinner      2,  6, 10, 14, 18, ...
snacks      3,  9, 11, 15, 19, ...

Assuming you want each of your meal types to get the sequence 0, 1, 2, ..., you should use something like:

BreakfastDR.push('.' + low +'.breakfast');
LunchDR.push('.' + low +'.lunch');
DinnerDR.push('.' + low +'.dinner');
SnacksDR.push('.' + low++ +'.snacks');

or, if you may want to add meals after snacks at some point:

BreakfastDR.push('.' + low +'.breakfast');
LunchDR.push('.' + low +'.lunch');
DinnerDR.push('.' + low +'.dinner');
SnacksDR.push('.' + low +'.snacks');
low++;

Upvotes: 3

TimWolla
TimWolla

Reputation: 32701

The reason is that you are incrementing low four times in your loop. Only increment it once at the end:

while (low <= high) {
    BreakfastDR.push('.' + low +'.breakfast');
    LunchDR.push('.' + low +'.lunch');
    DinnerDR.push('.' + low +'.dinner');
    SnacksDR.push('.' + low +'.snacks');
    low++;
}

Upvotes: 4

Related Questions