Javascript Enum To Corresponding String Value

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

    For TypeScript, there is a simpler solution (Please ignore my answer if you stick with JS):

    export enum Direction {
        none,
        left = 1,
        right = 2,
        top = 4,
        bottom = 8
    }
    
    export namespace Direction {
        export function toString(dir: Direction): string {
            return Direction[dir];
        }
    
        export function fromString(dir: string): Direction {
            return (Direction as any)[dir];
        }
    }
    
    console.log("Direction.toString(Direction.top) = " + Direction.toString(Direction.top));
    // Direction.toString(Direction.top) = top
    console.log('Direction.fromString("top") = ' + Direction.fromString("top"));
    // Direction.fromString("top") = 4
    console.log('Direction.fromString("xxx") = ' + Direction.fromString("unknown"));
    // Direction.fromString("xxx") = undefined
    
    

    Because the enumeration type is compiled into an object(dictionary). You don't need a loop to find the corresponding value.

    enum Direction {
        left,
        right
    }
    

    is compiled into:

    {
        left: 0
        right: 1
        0: "left",
        1: "right"
    }
    

提交回复
热议问题