如何改造以下场景 if-else 的代码?

2017-05-30 21:05:32 +08:00
 EXDestroyer

有一批物品数据,每个物品都有 id 字段,同时可能有 config 字段(如果没有这个字段则跳过忽略),用户每次会添加不同的物品 现在需要在用户添加的物品列表中,取出权重最高的那个 config 字段,并最后返回,其中: id 为 1、3 的物品权重最,2、4 次之,5、7 最低。。以此类推,可能还会有还有很多其他的 id

现在我个人的做法是,循环遍历

var config = null;

for (var item of items){
if (item['id'] === 1 || item['id'] === 3){
	config = config ? (item['config']?item['config']:null) : null
}else if (item['id'] === 2 || item['id'] === 4){
	config = config ? (item['config']?item['config']:null) : null
}...
}

但是这样太蠢。。有什么更好的模式可以取代这种操作吗,或者这种场景应该如何处理

4499 次点击
所在节点    JavaScript
22 条回复
ferrum
2017-05-30 21:08:18 +08:00
看看你这里写的代码,已经有一部分重复了,就把重复那部分提取出来,作为一个函数。
EXDestroyer
2017-05-30 21:10:05 +08:00
@ferrum 重复部分是可以优化,现在我比较头疼的是大量的 if else,不知道怎么处理更好
4641585
2017-05-30 21:13:11 +08:00
写成 Switch ?
印象中哪个课本上提到过条件嵌套的优化,然而已经记不清了
sumhat
2017-05-30 21:13:35 +08:00
nutting
2017-05-30 21:15:00 +08:00
map?然后排序?
EXDestroyer
2017-05-30 21:17:15 +08:00
@sumhat 这个思路挺好的,哈哈
gmywq0392
2017-05-30 21:29:29 +08:00
这么个法子不知道对不对。
先按照你业务约束的 id 权重顺序写个数组*。
然后做 table(或者说是 object)给他个 comparable 函数,具体就是用 item 的 id 去按照*的索引排序。然后再取该 table(或者说是 object)的 first item 不就…
8qwe24657913
2017-05-30 21:38:16 +08:00
@sumhat #4
var idLevel = Infinity;
function getIdLevel(id) {
return Math.ceil(id / 4) * 2 - id % 2
}
EXDestroyer
2017-05-30 21:40:46 +08:00
@8qwe24657913 这个权重是我假设的哈~其实真实情况不一定是有规律的权重
8qwe24657913
2017-05-30 21:49:28 +08:00
@EXDestroyer #9
var levels = {
id1:level1,
id2:level2,
};
function getIdLevel(id) {
return levels[id];
}
sagaxu
2017-05-30 21:56:14 +08:00
2000 个 id 你就写 1000 个 if-else?
wangxiaoer
2017-05-30 22:03:05 +08:00
这不就是 Items 排序?看样子是 js,那就写个排序函数 fun 不就完了? Fun 里面按你的 id 规则来

Items.sort(fun)
sensui7
2017-05-31 00:33:31 +08:00
if 语句可以用真值表简化
autoxbc
2017-05-31 02:32:17 +08:00
var config = null ;
[1,3,2,4,5,7].some(function(level){
return items.some(function(item){
if(item.config && item.id === level)
return config = item.config ;
});
});
alert(config);

只需要维护一个权重数组。
autoxbc
2017-05-31 02:38:27 +08:00
为什么 V2EX 歧视 Tab 缩进派

var config = null ;
[1,3,2,4,5,7].some(function(level){
return items.some(function(item){
if(item.config && item.id === level)
return config = item.config ;
});
});
alert(config);
autoxbc
2017-05-31 02:42:20 +08:00
全角空格缩进

var config = null ;
[1,3,2,4,5,7].some(function(level){
   return items.some(function(item){
     if(item.config && item.id === level)
       return config = item.config ;
  });
});
alert(config);
cxbig
2017-05-31 07:13:46 +08:00
恕我眼拙, 你这 1/3 和 2/4 的处理方式是一样的,那分不分有啥区别?
tangzhangming
2017-05-31 08:27:33 +08:00
@cxbig 我也是这样想的
araraloren
2017-05-31 08:58:54 +08:00
@cxbig 看到你这句话 我也突然发现,这 TM 一样的还 if 个屁阿
zhengxiaowai
2017-05-31 10:42:26 +08:00
google Strategy method

话说策略模式真是解决 if-else 的利器

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/364775

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX