首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript重构处理重复代码

Javascript重构处理重复代码
EN

Stack Overflow用户
提问于 2015-07-15 15:45:30
回答 1查看 36关注 0票数 0

我有以下代码:

代码语言:javascript
运行
复制
  switch(equipmentAttachment.AttachmentPosition)
  {
    case 'AttachFront':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.frontAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.frontAttachment=equipmentAttachment.ProductCategoryName;
      }
      break;
    }
    case 'AttachRear':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.backAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.backAttachment=equipmentAttachment.ProductCategoryName;
      }  
      break;        
    }
    case 'Tertiary':
    {
      if(equipmentAttachment.ProductCategoryDesc!='')
      {
        attachments.thirdAttachment=equipmentAttachment.ProductCategoryDesc;
      }
      else
      {
        attachments.thirdAttachment=equipmentAttachment.ProductCategoryName;
      }
      break;
    }
  }
  return attachments;

注意,对于对象attachments中不同属性的设置,大多数代码都是重复接受的。不管怎么说,有必要去掉重复的代码吗?还是真的是这样?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-15 16:00:54

代码语言:javascript
运行
复制
var posMap = {
  "AttachFront": "frontAttachment", 
  "AttachRear": "backAttachment", 
  "Tertiary": "thirdAttachment"
};
if(posMap[equipmentAttach.AttachmentPosition])
{
  var target = posMap[equipmentAttach.AttachmentPosition];
  attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;

更新:略为简洁:

代码语言:javascript
运行
复制
var target = {
  "AttachFront": "frontAttachment", 
  "AttachRear": "backAttachment", 
  "Tertiary": "thirdAttachment"
}[equipmentAttach.AttachmentPosition];
if(target)
{
  attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31435083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档