简体   繁体   中英

reduce multiple similar if/else statements - javascript

I have this piece of code, but I was wondering if there was a way to reduce the amount of lines?

function winResize(w) {
    if (w >= 250 && w < 500 ) { $('body').alterClass('col_*', 'col_1'); }
    if (w >= 500 && w < 750 ) { $('body').alterClass('col_*', 'col_2'); }
    if (w >= 750 && w < 1000 ) { $('body').alterClass('col_*', 'col_3'); }
    if (w >= 1000 && w < 1250 ) { $('body').alterClass('col_*', 'col_4'); }
    if (w >= 1250 && w < 1500 ) { $('body').alterClass('col_*', 'col_5'); }
    if (w >= 1500 && w < 1750 ) { $('body').alterClass('col_*', 'col_6'); }
    if (w >= 1750 && w < 2000 ) { $('body').alterClass('col_*', 'col_7'); }
    if (w >= 2000 && w < 2250 ) { $('body').alterClass('col_*', 'col_8'); }
    if (w >= 2250 && w < 2500 ) { $('body').alterClass('col_*', 'col_9'); }
    if (w >= 2500 ) { $('body').alterClass('col_*', 'col_10'); }
}

This is how I call the function

winResize(window.innerWidth);

It looks like your intervals are multiples of 250. You can use that to advantage:

function winResize(w) {
    var index = Math.min(10, Math.floor(w / 250));
    if (index > 0) {
        $('body').alterClass('col_*', 'col_' + index);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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