亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在打字稿中編寫此開關/案例的更好方法?

在打字稿中編寫此開關/案例的更好方法?

繁星coding 2021-06-22 16:42:46
我正在 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;    }}
查看完整描述

3 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

請考慮使用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"; 

    }

}

祝你今天過得愉快!


查看完整回答
反對 回復 2021-06-24
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

您可以根據鍵創建對象和訪問屬性


let WeatherCodition = {

  thunderstorm:"thunderstorm.png",

  clouds:"clouds.png",

  drizzle:"drizzle.png",

  rain:"rain.png",

  snow:"snow.png",

  default:"clear.png"

}


function getIcon(condition) {

  condition = condition || ""

  condition = Object.keys(WeatherCodition).find(c=> c.toLowerCase() === condition.toLowerCase()) || 'default'

  return WeatherCodition[condition]

}


console.log(getIcon(''))

console.log(getIcon('Clouds'))

console.log(getIcon())

console.log(getIcon('SnoW'))


查看完整回答
反對 回復 2021-06-24
  • 3 回答
  • 0 關注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號