美文网首页
switch结构采用对象形式重写

switch结构采用对象形式重写

作者: wangxingkang | 来源:发表于2016-07-05 22:56 被阅读39次

原因

  • switch结构不利于代码重用
  • 对象属性写法更加简洁

例子

swith写法

function getItemPricing(customer, item) { 
      switch(customer.type) { 
           case 'VIP': 
                   return item.price * item.quantity * 0.50; 
                   break;
           case 'Preferred': 
                   return item.price * item.quantity * 0.75; 
                   break;
           case 'Regular': 
           default: return item.price * item.quantity;
      }
}  

对象属性写法

var pricing = { 
         'VIP': 0.50,
         'Preferred': 0.75,
         'Regular': 1.0
};

function getItemPricing(customer, item) { 
       if (pricing[customer.type]) {
               return item.price * item.quantity * pricing[customer.type]; 
       }else {
               return item.price * item.quantity * pricing.Regular;
       } 
}                                                                               

相关文章

网友评论

      本文标题:switch结构采用对象形式重写

      本文链接:https://www.haomeiwen.com/subject/egxkjttx.html