【问题标题】:How can I use enum values as index of array如何使用枚举值作为数组的索引
【发布时间】:2019-11-17 16:36:21
【问题描述】:

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

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.

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

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

【问题讨论】:

  • 那不是枚举。而Color.RED 不是Color 的实例。
  • 如果我删除 export 关键字,在 Chrome 中的纯 JS 中对我有用
  • @mplungjan 在这里也一样。但不是在 Firefox 中 - 它报告尚不支持字段。
  • 只有当你有x[Color]而不是x[Color.RED]Typescript Playground时才会显示这个错误

标签: javascript arrays enums array-indexing


【解决方案1】:

要创建一个枚举,我们创建一个 const 冻结对象。有关差异以及原因,请参见以下引用:

const 适用于绑定(“变量”)。它创建了一个不可变的 绑定,即您不能为绑定分配新值。

Object.freeze 作用于值,更具体地说,作用于对象值。 它使对象不可变,即您无法更改其属性。

发件人:https://stackoverflow.com/a/33128023/9758920

之后我们仍然可以像访问普通对象一样访问键和值。

// https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript
const COLORS = Object.freeze({"RED":0, "BLUE":1, "GREEN":2})

let x = ['warning', 'info', 'success'];
let anotherVariable = x[COLORS.RED]; 

console.log(anotherVariable)

另请查看:https://stackoverflow.com/a/49309248/9758920

【讨论】:

  • 这不能回答为什么发布的代码会抛出错误
  • 从 cmets 看:很可能是浏览器支持问题。
【解决方案2】:

试试这个。

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

    module.exports = color

    let x = ['warning', 'info', 'success'];
    let anotherVariable = x[color.RED];

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 2016-06-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2012-03-13
    相关资源
    最近更新 更多