0

I want javascript functions which take integer (week days[i.e 1,2,3...7 ]) and return string (i.e 'Sunday','Monday'....) . but I dont know what are the best way to do this. it means what I should use enum or array or switch case

  • Js function
  • function GetFullName(weekDay) { if (weekDay == 1) return "Monday";
    if (WeekDay = 2)
    return "Tuesday"; }

  • But, I dont want to do like this......Is there any smart way to thi using create Enum ?

1
  • Just use an array, if Monday needs to start at 1 use an object Commented Sep 11, 2014 at 10:30

2 Answers 2

3

try this

function GetFullName(weekDay)
{
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var day = days[ weekDay-1];
return day;
}
Sign up to request clarification or add additional context in comments.

3 Comments

If you want to use days as in 1st, 2nd... etc. you will have to add a -1 like days[weekDay-1];
@Spokey You mean days[weekDay-1] :)
@RGraham Yes indeed, simple logic error. Should be -1
2

Just another thought than array, create an object weekday with dayname and 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);

1 Comment

Thanks , this will also help me when my js function take short name instead int i have modify it little and it's works for me . If my function is taking short name like 'Mon','Thu' etc. than this function is useful .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.