选择if else else条件javaScript

时间:2017-04-27 07:44:54

标签: javascript typescript

我有一个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;
    }

4 个答案:

答案 0 :(得分:4)

使用数组......

function dayNumberToString(dayNumber) {
    return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'][dayNumber % 7]
}

答案 1 :(得分:3)

有一个查找表:

const dayNames = [ "Sunday", "Monday", "Tuesday", .... ]
console.log(dayNames[1]) // gives you Monday

[1,0,2].map(x => dayNames[x])  // converts an array of day numbers

答案 2 :(得分:3)

在数组中保存天数,并使用变量

对其进行索引
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;
}

答案 3 :(得分:1)

这正是TypeScript enum的用途。

// outside the class
enum Day { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

class Foo {
  private _convertIntToStringDays(days: number[]) {
    return days.map(day => Day[day]);
  }
}

作为参考,TS将枚举转换为以下内容,允许双向查找:

var Day;
(function (Day) {
    Day[Day["sunday"] = 0] = "sunday";
    Day[Day["monday"] = 1] = "monday";
    Day[Day["tuesday"] = 2] = "tuesday";
    Day[Day["wednesday"] = 3] = "wednesday";
    Day[Day["thursday"] = 4] = "thursday";
    Day[Day["friday"] = 5] = "friday";
    Day[Day["saturday"] = 6] = "saturday";
})(Day || (Day = {}));