
有一批物品数据,每个物品都有 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 }... } 但是这样太蠢。。有什么更好的模式可以取代这种操作吗,或者这种场景应该如何处理
1 ferrum 2017-05-30 21:08:18 +08:00 via iPhone 看看你这里写的代码,已经有一部分重复了,就把重复那部分提取出来,作为一个函数。 |
2 EXDestroyer OP @ferrum 重复部分是可以优化,现在我比较头疼的是大量的 if else,不知道怎么处理更好 |
3 4641585 2017-05-30 21:13:11 +08:00 写成 Switch ? 印象中哪个课本上提到过条件嵌套的优化,然而已经记不清了 |
4 sumhat 2017-05-30 21:13:35 +08:00 |
5 nutting 2017-05-30 21:15:00 +08:00 via Android map?然后排序? |
6 EXDestroyer OP @sumhat 这个思路挺好的,哈哈 |
7 gmywq0392 2017-05-30 21:29:29 +08:00 via Android 这么个法子不知道对不对。 先按照你业务约束的 id 权重顺序写个数组*。 然后做 table(或者说是 object)给他个 comparable 函数,具体就是用 item 的 id 去按照*的索引排序。然后再取该 table(或者说是 object)的 first item 不就… |
8 8qwe24657913 2017-05-30 21:38:16 +08:00 |
9 EXDestroyer OP @8qwe24657913 这个权重是我假设的哈~其实真实情况不一定是有规律的权重 |
10 8qwe24657913 2017-05-30 21:49:28 +08:00 |
11 sagaxu 2017-05-30 21:56:14 +08:00 2000 个 id 你就写 1000 个 if-else? |
12 wangxiaoer 2017-05-30 22:03:05 +08:00 via Android 这不就是 Items 排序?看样子是 js,那就写个排序函数 fun 不就完了? Fun 里面按你的 id 规则来 Items.sort(fun) |
13 sensui7 2017-05-31 00:33:31 +08:00 if 语句可以用真值表简化 |
14 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); 只需要维护一个权重数组。 |
15 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); |
16 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); |
17 cxbig 2017-05-31 07:13:46 +08:00 via Android 恕我眼拙, 你这 1/3 和 2/4 的处理方式是一样的,那分不分有啥区别? |
18 tangzhangming 2017-05-31 08:27:33 +08:00 @cxbig 我也是这样想的 |
19 araraloren 2017-05-31 08:58:54 +08:00 @cxbig 看到你这句话 我也突然发现,这 TM 一样的还 if 个屁阿 |
21 HsuanLee 2017-05-31 23:33:11 +08:00 |
22 HsuanLee 2017-05-31 23:36:56 +08:00 哦,题主说的优化 if-else,我这个没用 if-else 算不算优化? |