字典和声明变量
Dictionaries and declaring vars
我有各种针对不同屏幕尺寸的变量:
ST.screen_x_small = 480;
ST.screen_small = 768;
ST.screen_medium = 992;
ST.screen_large = 1200;
我想声明每个变量要加载的项目数。例如,如果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];
}
我的问题是:
有没有更好的方法可以做到这一点?
有没有更有效的方法来声明字典?理想情况下,我只想在 ST.screen_x_small var 中声明 480,而不是在字典中再次声明。
基于 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;
}
});
将维度和关联的数据放入数组中的对象中,必要时进行排序,然后遍历该数组,这样就不必为任何新项键入其他条件。
您可以将它们合并到一个字典中,如下所示:
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;
}
相关文章:
- 使用同一对象中的其他变量声明变量
- 如何将变量声明为全局变量
- 如何将变量声明为全局变量?用case foreach?Javascript
- 理解bootstrap.js变量声明
- 将 Javascript 变量声明为 PHP 形式
- 单个逗号分隔的变量声明和多个声明之间的区别是什么
- Do变量声明初始化函数
- Javascript变量声明:什么是“;var myVariable={}”;
- javascript中不同类型的变量声明
- 为什么在循环的Javascript中包含变量声明
- for 循环中必需的变量声明
- JavaScript 中的变量声明
- 在 Javascript 变量声明中使用逗号
- 你能在变量声明中添加条件吗?
- JavaScript 全局变量声明
- 节点.js变量声明和作用域
- 具有多个逗号分隔值的变量声明是什么意思(例如 var a = b,c,d;)
- 移动图像 ..JavaScript 将变量声明为字符串
- 让 javascript 将(默认情况下)未声明的变量声明到当前本地范围(基于首次使用)而不是全局范围
- 循环中的变量声明