gpt4 book ai didi

javascript - 用 typescript 写这个开关/案例的更好方法?

转载 作者:行者123 更新时间:2023-11-30 19:30:04 31 4
gpt4 key购买 nike

我正在 Angular 中开发一个非常简单的天气应用程序,我想问你是否认为有更好的方法来根据天气条件的“类型”选择特定图像。

enum WeatherCodition {
Thunderstorm = 0,
Drizzle,
Rain,
Snow,
Clear,
Clouds
}

export class Weather {


getIcon(condition: WeatherCodition): string {

var iconPath = "";
switch(condition){
case WeatherCodition.Thunderstorm:
iconPath = "thunderstorm.png";
break;
case WeatherCodition.Clouds:
iconPath = "clouds.png";
break;
case WeatherCodition.Drizzle:
iconPath = "drizzle.png";
break;
case WeatherCodition.Rain:
iconPath = "rain.png";
break;
case WeatherCodition.Snow:
iconPath = "snow.png";
break;
default:
iconPath = "clear.png"
}

return iconPath;
}

}

最佳答案

请考虑使用 interface KeyValue<K, V>作为数组。我的解决方案:

export enum WeatherCodition {
Thunderstorm = 0,
Drizzle,
Rain,
Snow,
Clear,
Clouds
}

import { KeyValue } from '@angular/common';

export class Weather {

public keyValueArray: KeyValue<WeatherCodition, string>[] =
[
{ key: WeatherCodition.Thunderstorm, value: "thunderstorm.png" },
{ key: WeatherCodition.Drizzle , value: "drizzle.png"},
{ key: WeatherCodition.Rain, value: "rain.png" },
{ key: WeatherCodition.Snow, value: "snow.png" },
{ key: WeatherCodition.Clear, value: "clear.png" },
{ key: WeatherCodition.Clouds, value: "clouds.png" },
];

getIcon(condition: WeatherCodition): string {
//check if 'condition' exists in array as key
return this.keyValueArray[condition] ?
this.keyValueArray[condition].value :
"clear.png";
}
}

祝你有美好的一天!

关于javascript - 用 typescript 写这个开关/案例的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56514950/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com