prog1011
prog1011

Reputation: 3495

How to create enum in javascript?

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

Upvotes: 0

Views: 3978

Answers (2)

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

try this

function GetFullName(weekDay)
{
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var day = days[ weekDay-1];
return day;
}

Upvotes: 3

SSA
SSA

Reputation: 5493

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);

Upvotes: 2

Related Questions