为什么这个.push()没有按预期工作?

时间:2014-03-17 01:28:27

标签: javascript jquery

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);
}

这是以4为间隔添加值。因此,如果low为0且high为16,则添加的字符串为:.0.breakfast,.4.breakfast,.8.breakfast,.12.breakfast

它应该以这种方式执行每个数字,而不仅仅是间隔为4. .0.breakfast,.1.breakfast,.2.breakfast,etc

有谁看到了明显的原因?我不应该在同一while function ??

中推进不同的变量

2 个答案:

答案 0 :(得分:4)

原因是你在循环中增加low四次。只在结尾处增加一次:

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

答案 1 :(得分:3)

这是因为您使用以下代码递增low 四次次,每次用餐后输入一次

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.

所以早餐会得到0,午餐会得到1等等。初始之后的下一个早餐将获得4。你最终会得到:

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

假设您想要每种您的膳食类型获得序列0, 1, 2, ...,您应该使用以下内容:

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

或者,如果你想在某些时候在零食后加入食物:

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