我如何使用枚举值作为数组的索引

sal*_*lly 6 javascript arrays enums array-indexing

我尝试使用枚举值作为数组的索引,但它给了我一个错误。

export class Color {
    static RED = 0;
    static BLUE = 1;
    static GREEN = 2;
}

let x = ['warning', 'info', 'success'];
let anotherVariable = x[Color.RED]; <---- Error: Type 'Color' cannot be used as an index type.
Run Code Online (Sandbox Code Playgroud)

我尝试了Number()和parseInt转换为数字,但是它不起作用。

有什么方法可以将Enum值用作索引?

小智 0

尝试这个。

    let color = {
        RED : 0,
        BLUE : 1,
        GREEN : 2
    }

    module.exports = color

    let x = ['warning', 'info', 'success'];
    let anotherVariable = x[color.RED];
Run Code Online (Sandbox Code Playgroud)