我如何反应这段代码,以免我重复dailogObj.image
?如果不是案例5,我会写一个return
语句,我有两个作业。
getDialogData(imageNum): any {
const dailogObj = {
image: '',
buttonName: 'Learn More'
};
switch (imageNum) {
case 1:
dailogObj.image = '../../../assets/images/Red-Image.png';
break;
case 2:
dailogObj.image = '../../../assets/images/blue-image-orgl.png';
break;
case 3:
dailogObj.image = '../../../assets/images/Green-Image-2.png';
break;
case 4:
dailogObj.image = '../../../assets/images/Gold-Image.png';
break;
case 5:
dailogObj.image = '../../../assets/images/green-img-orgl.png';
dailogObj.buttonName = 'Read Her Story';
break;
case 6:
dailogObj.image = '../../../assets/images/Red-Image-2.png';
break;
case 7:
dailogObj.image = '../../../assets/images/Blue-Image-2.png';
break;
case 8:
dailogObj.image = '../../../assets/images/Gold-Image-2.png';
break;
}
return dailogObj;
}
答案 0 :(得分:6)
您可以将该分配提取到自己的条件,只需使用数组来设置image
属性:
getDialogData(imageNum): any {
const dailogObj = {
image: '',
buttonName: 'Learn More'
};
// Handle the default case if imageNum is not in range [1..9]
if (imageNum >=1 && imageNum <=9) {
// Special treatment of image number 5
if (imageNum == 5) {
dailogObj.buttonName = 'Read Her Story';
}
// If it is in range, pick the right image:
var images =
['../../../assets/imfages/Red-Image.png',
'../../../assets/images/blue-image-orgl.png',
'../../../assets/images/Green-Image-2.png',
'../../../assets/images/Gold-Image.png',
'../../../assets/images/green-img-orgl.png',
'../../../assets/images/Red-Image-2.png',
'../../../assets/images/Blue-Image-2.png',
'../../../assets/images/Gold-Image-2.png'];
dailogObj.image = images[imageNum - 1];
}
return dailogObj;
}
答案 1 :(得分:0)
images = {
1: '../../../assets/images/Red-Image.png',
2: '../../../assets/images/blue-image-orgl.png',
...
8: '../../../assets/images/Gold-Image-2.png'
};
dailogObj.image = images[imageNum];
dailogObj.buttonName = imageNum == 5 ? 'Read Her Story' : 'Learn More';
或者您可以创建另一个对象来存储按钮名称,就像图像路径一样。