Javascript Enum To Corresponding String Value

前端 未结 8 1985
攒了一身酷
攒了一身酷 2021-01-07 17:06

So I have this in the javascript for my page:

var TEST_ERROR  = {
        \'SUCCESS\'   :   0,
        \'FAIL\'      :   -1,
        \'ID_ERROR\'  :   -2
            


        
相关标签:
8条回答
  • 2021-01-07 17:44

    The best way to do it is:

    export const UserLevel = Object.freeze({
       BABY: 1,
       CHILED: 2
    });
    

    Why we need to add freeze UserLevel is const but we can change the values inside, so freeze will make it safe for changes.

    0 讨论(0)
  • 2021-01-07 17:45

    If you are typescript, then you will already have a definition for the enum. Else you can directly use the JS version of the enum.

    var Status;
    (function (Status) {
        Status[Status["New"] = 0] = "New";
        Status[Status["Submitted"] = 1] = "Submitted";
        Status[Status["Approved"] = 2] = "Approved";
        Status[Status["Rejected"] = 3] = "Rejected";
    })(Status || (Status = {}));
    var snew = Status.New;
    console.log(snew); //This is the number
    console.log(Status[snew]); //This is the string
    
    0 讨论(0)
提交回复
热议问题