简体   繁体   English

减少多个类似的if / else语句-javascript

[英]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: 看来您的间隔是250的倍数。您可以使用该间隔来发挥优势:

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

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

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