2013-10-30 43 views
1

我有不同屏幕尺寸的各種瓦爾的:字典並宣佈瓦爾

ST.screen_x_small = 480; 
ST.screen_small = 768; 
ST.screen_medium = 992; 
ST.screen_large = 1200; 

我想申報一批項目的每VAR加載。因此,例如,如果x_small我想加載10,如果小,20等等。

我已經把每個尺寸在字典:

ST.content_per_load_dict = {'480' : 10, '768' : 20, '992' : 30, '1200' : 40}; 

然後:

var pageWidth = $(window).width(); 

    if(pageWidth < ST.screen_x_small) 
    { 
     ctx.contentPerLoad = ST.content_per_load_dict[ST.screen_x_small]; 
    } 
    else if(pageWidth < ST.screen_small) 
    { 
     ctx.contentPerLoad = ST.content_per_load_dict[ST.screen_small]; 
    } 
    else if(pageWidth < ST.screen_medium) 
    { 
     ctx.contentPerLoad = ST.content_per_load_dict[ST.screen_medium]; 
    } 
    else 
    { 
     ctx.contentPerLoad = ST.content_per_load_dict[ST.screen_large]; 
    } 

我的問題是:

  1. 有沒有更好的方式來做到這個?

  2. 是否有更有效的方法來聲明字典?理想情況下,我只想在ST.screen_x_small var中聲明480,而不是在字典中再次聲明。

回答

2

在pax162的回答大廈,你甚至可以進一步簡化這個操作。

// Order matters. 
var ST = [ {name: 'x-small', width: 480, items: 10}, {name: 'small', width: 768, items: 20} ]; 
// ST.sort(function(a,b) { return a.width > b.width }) 

ST.some(function (d) { 
    if(pageWidth <= d.width) { 
     ctx.contentPerLoad = d.items; 
     return true; 
    } 
}); 

把你的尺寸和相關數據爲對象的數組中,排序如果必要的話,然後遍歷數組,這樣您就不必爲任何新項目鍵入了更多的條件。

+0

謝謝,什麼是評論排序位? – panthro

+0

正如我所提到的那樣,如果有必要,您可以這樣分類。如果數組已經預先分類,那麼就沒有必要這樣做。 –

+0

所以我正確思考.some只是遍歷數組?直到滿足條件? – panthro

0

你可以把它們合併成一個單一的字典,像這樣:

var ST = { 
    screen_x_small: { 
     width: 480, 
     items:10 
    }, 
    screen_small: { 
     width: 768, 
     items:20 
    }, 
} 

然後:

if(pageWidth < ST.screen_x_small.width) 
{ 
    ctx.contentPerLoad = ST.screen_x_small.items; 
} 
else if(pageWidth < ST.screen_small.width) 
{ 
    ctx.contentPerLoad = ST.screen_small.items; 
}