猿问

在打字稿中编写此开关/案例的更好方法?

我正在 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;

    }


}


繁星coding
浏览 163回答 3
3回答

ITMISS

请考虑使用interface KeyValue<K, V>作为数组。我的解决方案:export enum WeatherCodition {&nbsp; &nbsp; Thunderstorm = 0,&nbsp; &nbsp; Drizzle,&nbsp; &nbsp; Rain,&nbsp; &nbsp; Snow,&nbsp; &nbsp; Clear,&nbsp; &nbsp; Clouds}import { KeyValue } from '@angular/common';export class Weather {&nbsp; &nbsp; public keyValueArray: KeyValue<WeatherCodition, string>[] =&nbsp;&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Thunderstorm, value: "thunderstorm.png" },&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Drizzle , value: "drizzle.png"},&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Rain, value: "rain.png" },&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Snow, value: "snow.png" },&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Clear, value: "clear.png" },&nbsp; &nbsp; &nbsp; &nbsp; { key: WeatherCodition.Clouds, value: "clouds.png" },&nbsp; &nbsp; ];&nbsp; &nbsp; getIcon(condition: WeatherCodition): string {&nbsp; &nbsp; &nbsp; &nbsp; //check if 'condition' exists in array as key&nbsp; &nbsp; &nbsp; &nbsp; return this.keyValueArray[condition] ?&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.keyValueArray[condition].value :&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "clear.png";&nbsp;&nbsp; &nbsp; }}祝你今天过得愉快!

波斯汪

您可以根据键创建对象和访问属性let WeatherCodition = {&nbsp; thunderstorm:"thunderstorm.png",&nbsp; clouds:"clouds.png",&nbsp; drizzle:"drizzle.png",&nbsp; rain:"rain.png",&nbsp; snow:"snow.png",&nbsp; default:"clear.png"}function getIcon(condition) {&nbsp; condition = condition || ""&nbsp; condition = Object.keys(WeatherCodition).find(c=> c.toLowerCase() === condition.toLowerCase()) || 'default'&nbsp; return WeatherCodition[condition]}console.log(getIcon(''))console.log(getIcon('Clouds'))console.log(getIcon())console.log(getIcon('SnoW'))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答