我有以下代码:
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
中不同属性的设置,大多数代码都是重复接受的。不管怎么说,有必要去掉重复的代码吗?还是真的是这样?
发布于 2015-07-15 16:00:54
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;
更新:略为简洁:
var target = {
"AttachFront": "frontAttachment",
"AttachRear": "backAttachment",
"Tertiary": "thirdAttachment"
}[equipmentAttach.AttachmentPosition];
if(target)
{
attachments[target] = (equipmentAttachment.ProductCategoryDesc || equipmentAttachment.ProductCategoryName);
}
return attachments;
https://stackoverflow.com/questions/31435083
复制相似问题