我希望javascript函数占用
integer
(周日[即1,2,3 ... 7] )并返回string
(即& #39;星期天'星期一' ....)。但我不知道最好的办法是什么。它意味着我应该使用enum
或array
或switch case
function GetFullName(weekDay) {
if (weekDay == 1)
return "Monday";
if (WeekDay = 2)
return "Tuesday";
}
但是,我不想这样做......有没有聪明的方法来使用创建Enum
?
答案 0 :(得分:3)
试试这个
function GetFullName(weekDay)
{
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var day = days[ weekDay-1];
return day;
}
答案 1 :(得分:2)
只是另一个想法而不是数组,用dayname和index创建一个工作日:
var weekdays = {
Monday : 1,
Tuesday : 2,
Wednesday : 3,
Thursday:4,
Friday:5,
Saturday:6,
Sunday:7
}
function getFullName(weekDay) {
for( var prop in weekdays ) {
if( weekdays.hasOwnProperty( prop ) ) {
if( weekdays[ prop ] === weekDay )
return prop;
}
}
}
var fullName = getFullName(2);
console.log(fullName);