3 回答
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";
}
}
祝你今天过得愉快!
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'))
添加回答
举报