简体   繁体   English

为什么这个.push()无法正常工作?

[英]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 这将以4为间隔添加值。因此,如果low为0且high为16,则添加的字符串为: .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 它应该以这种方式处理每个数字,而不仅仅是以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 ?? 我不应该在同一个while function放入不同的var吗?

The reason is that you are incrementing low four times in your loop. 原因是您在循环中low四次递增。 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++;
}

It's because you're incrementing low four times with the following code, once after each meal type: 这是因为您在每次进餐类型之后都使用以下代码将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.

So breakfast will get 0 , lunch will get 1 and so on. 因此早餐将变为0 ,午餐将变为1 ,依此类推。 The next breakfast after the initial one will get 4 . 最初的早餐后的下一个早餐将得到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: 假设您希望每种进餐类型的顺序为0, 1, 2, ... ,则应使用类似以下内容的方法:

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++;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM