javascript - 最佳实践:对象与开关
问题描述
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;
}
解决方案
你想要的是这样的东西:
const VIDEOS = {
'the red hot chili peppers': 'yOYmdyaSOCg',
'Freaky Styley': '3Z4JUqA_bKE',
...
}
function takeVideo(currentAlbum: keyof typeof VIDEOS) {
this.video.id = VIDEOS[currentAlbum];
}
还要注意的类型currentAlbum: keyof typeof VIDEOS
- 这使得即使调用takeVideo
也被检查,即
takeVideo('Freaky Styley'); // is valid
takeVideo('some unknown title'); // is invalid - type error
推荐阅读
- python-3.x - Pandas:取具有匹配值的行的平均值
- javascript - 如何发布 Ajax 请求
- sql - Hibernate DDL 更新 SQL 查询
- math - R 编程语言有这种语法吗?
- javascript - 如何使用代码点火器 fromework 在 PHP 中打印出模态内部的内容
- angular - 如何避免使用 Visual Studio 2017 在 Angular 4 的生产模式下加载 node_modules 和 .ts 文件
- json - Cloudformation,模板验证错误:无效的模板属性或属性
- android - 用于 fastboot 和 adb 的 Windows 10 原始 USB 访问
- c# - 如何让眼睛随机眨眼?
- css - 删除材质对话框上的奇怪边框