Javascript Enum To Corresponding String Value

前端 未结 8 2058
攒了一身酷
攒了一身酷 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:30

    This might be different from what you want but I want to share my answer. This was inspired by @LukeHconst solution. Consider bookCategory below you will notice that I'm using a number as a key.

    const bookCategory = {
        "0": "Biography",
        "1": "Fiction",
        "2": "History",
        "3": "Mystery",
        "4": "Suspense",
        "5": "Thriller"
    };
    

    I wrote the bookCategory like this because if you are using an enum column in MySQL. For example,

    category ENUM ('0', '1', '2', '3', '4', '5')
    

    You would need some kind of conversion in JavaScript. So I came up with this and the usage is simple as:

    bookCategory[book.category]
    

提交回复
热议问题