currentAlbum: string | undefined;
video: any = { id: 'TYYW_WwYHuM' };
我正在努力改进我的代码,我写了一个很长很难看的开关,我想把它变成一个语法更好的对象。
但我想知道,为什么我要在函数中写下它:
takeVideo(currentAlbum: string | undefined): void {
switch (this.currentAlbum) {
case 'the red hot chili peppers':
this.video.id = 'yOYmdyaSOCg';
break;
case 'Freaky Styley':
this.video.id = '3Z4JUqA_bKE';
break;
case 'The Uplift Mofo Party Plan':
this.video.id = 'a8DPkw5Nc64';
break;
case "Mother's Milk":
this.video.id = 'HZySqMlEuSQ';
break;
case 'Blood Sugar Sex Magik':
this.video.id = 'Mr_uHJPUlO8';
break;
case 'One Hot Minute':
this.video.id = 'vV8IAOojoAA';
break;
case 'Californication':
this.video.id = 'mzJj5-lubeM';
break;
case 'By the Way':
this.video.id = 'JnfyjwChuNU';
break;
case 'Stadium Arcadium':
this.video.id = 'oDNcL1VP3rY';
break;
case "I'm with You":
this.video.id = 'qOgFHMEJMeY';
break;
case 'The Getaway':
this.video.id = 'Q0oIoR9mLwc';
break;
default:
this.video.id = 'TYYW_WwYHuM';
}
}
但是如果我写这篇文章,这应该是最好的实践,不是吗?
takeVideo(currentAlbum: string | undefined): void {
const videos = {
'the red hot chili peppers': (this.video.id = 'yOYmdyaSOCg'),
'Freaky Styley': (this.video.id = '3Z4JUqA_bKE'),
'The Uplift Mofo Party Plan': (this.video.id = 'a8DPkw5Nc64'),
"Mother's Milk": (this.video.id = 'HZySqMlEuSQ'),
'Blood Sugar Sex Magik': (this.video.id = 'Mr_uHJPUlO8'),
'One Hot Minute': (this.video.id = 'vV8IAOojoAA'),
'Californication': (this.video.id = 'mzJj5-lubeM'),
'By the Way': (this.video.id = 'JnfyjwChuNU'),
'Stadium Arcadium': (this.video.id = 'oDNcL1VP3rY'),
"I'm with You": (this.video.id = 'qOgFHMEJMeY'),
'The Getaway': (this.video.id = 'Q0oIoR9mLwc'),
};
return videos[currentAlbum] ?? this.video.id;
}
2条答案
按热度按时间kgsdhlau1#
首先,使用对象而不是switch语句不是最佳实践。
这取决于你在哪里使用它。
其次,您应该将函数与赋值一起使用,而不是与赋值一起使用。就是
这是因为代码的赋值都是在定义时执行的
videos
.现在,我认为这段代码比您试图做的要好得多
m528fe3b2#
你想要的是这样的:
还要注意
currentAlbum: keyof typeof VIDEOS
-这使得即使打电话takeVideo
是否已检查类型,即。