我有一个TypeScript方法。它将整数值转换/映射为字符串天。我如何才能将此代码改进为更有效的方法?任何的想法?
private _convertIntToStringDays(days: any){
let dayArray: any = [];
for (let day in days){
if (days[day] == 1){
dayArray.push('monday');
}
else if (days[day] == 2){
dayArray.push('tuesday');
}
else if (days[day] == 3){
dayArray.push('wednesday');
}
else if (days[day] == 4){
dayArray.push('thursday');
}
else if (days[day] == 5){
dayArray.push('friday');
}
else if (days[day] == 6){
dayArray.push('saturday');
}
else if (days[day] == 0){
dayArray.push('sunday');
}
}
dayArray.shift(dayArray[0]);
console.log(dayArray);
return dayArray;
}
最佳答案
将天的名称保存在数组中,并使用变量将其编入索引
private _convertIntToStringDays(days: any) {
let dayArray: any = [];
let dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
for (let day in days){
dayArray.push(dayNames[days[day]]);
}
dayArray.shift(dayArray[0]);
console.log(dayArray);
return dayArray;
}