开发者

Javascript loop with dynamic start and end variables

This seems pretty basic, but I can't find the best method to do th开发者_如何学运维is... I'm trying to set up a function that loops between a user selected start and end variables. This is what I ended up with but I'm sure there is a better way to do it (demo).

Note: the x & y variables are indexed to one, not zero.

getWidths1 = function(x, y) {
    var start = (x < y) ? x : y,
        end = (x < y) ? y : x,
        total = 0;
    for (; start < end; start++) {
        total += values[start - 1] || 0;
    }
    return total;
};

I tried this function, but the results are one result off when y > x:

getWidths2 = function(x, y) {
    var total = 0,
        diff = (x < y) ? 1 : -1;
    while (x !== y) {
        total += values[x - 1] || 0;
        x += diff;
    }
    return w;
};

So, is the first function the best, or does someone have a better method?


The first isn't bad. I think this is slightly more traditional:

for (var i = start; i < end; i++){

}

Only real difference is that it doesn't affect start and end.


I'd make a few changes:

Use Math.min and Math.max - much more readable.

Don't subtract one from start if the first value you want is values[start].

var getWidths1 = function(x, y) {
    var start = Math.min(x,y), end = Math.max(x,y);
    var total = 0;
    for (; start < end; start++) {
        total += values[start] || 0;
    }
    return(total);
}


I agree with @kingjiv with the added caveat that if you want to include the item at y then you need:

for (var i = start; i <= end; i++){
...
}

As it is your code (both versions) will total the values from x inclusive to y exclusive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜