2017-04-27 57 views
2

我有一個TypeScript方法。它將整數值轉換/映射到字符串天。我該如何將此代碼改進爲更高效的代碼?任何想法?optmise if else條件javaScript

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; 
    } 
+0

看起來更像是打字稿或流動到我... – haim770

+0

對不起它打字稿 – blackdaemon

+0

日子我得到是整數值 – blackdaemon

回答

3

保存名稱...

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

使用'map'會更好...... – Alnitak

+0

@Alnitak同意你的觀點,但我只提供了一個例子,對原始代碼進行必要的更改 –

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; 
} 
+1

'dayNames [days [day]]' – devnull69

+0

OP的函數需要一個數組並返回一個匹配的數組 – haim770

+2

@ haim770這個答案有足夠多的信息來解決這個問題,而不用勺子把它餵給OP – Alnitak

4

使用陣列

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 
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 transpiles枚舉成以下,使雙向查詢:

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 = {}));