将判断及处理定义为一个策略对象,key为判断条件,值为函数,可带参。

var strategy = {
'a':function(count){
return count*1;
},
'b':function(count){
return count*2;
},
'c':function(count){
return count*3;
}
}
//定义一个函数接收判断条件及参数
var calculate = function(level,count){
return strategy[level](count);//找到对应条件的函数并执行
}

console.log(calculate('a',1));//1
console.log(calculate('b',1));//2

这样写的好处是,代码中减少了大量if/else语句;可扩展性好;
写if/else语句会基于判断一个一个对比,倘若判断多,且匹配条件刚好又处于靠后位置,势必会影响效率。
至于采用对象查找key值,有人试验查找一个具有300000个字符串的键值对,查找速率小于1ms。

相关文章:

  • 2021-06-22
  • 2021-11-11
  • 2022-12-23
  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2021-04-10
猜你喜欢
  • 2021-08-19
  • 2023-03-08
  • 2022-01-24
  • 2021-11-08
  • 2021-12-06
相关资源
相似解决方案