Javascript Enum To Corresponding String Value

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

    Not quite optimal, but the cleanest you can get without pre-computing the reverse dictionary (and besides, this shouldn't be too much of an issue if you only have a few enumeration values):

    function string_of_enum(enum,value) 
    {
      for (var k in enum) if (enum[k] == value) return k;
      return null;
    }
    

提交回复
热议问题