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

标签 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.

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

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

最佳答案

为了创建一个枚举,我们创建了一个常量卡住对象。对于差异和原因,请参阅以下引用:

const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value to the binding.

Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.

发件人: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

关于javascript - 如何使用枚举值作为数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930230/

相关文章:

javascript - 如何使用提示输入循环遍历对象数组并显示属性

javascript - 在 JavaScript 中使用 .filter 评估传递的值

javascript - 给定对象 : let obj = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5}; Convert the keys of this object in one array, 和另一个中的值

java - 什么是表示比枚举更复杂但又不完全是类的字段的良好数据结构?

javascript - 在浏览器上显示服务器时间而不是客户端时间

javascript - AG-GRID 单元格在第二次编辑后仅显示错误边框和工具提示

C程序将空格分隔的输入字符串转换为int数组

java - 尝试使用 hashmap 来计算数组中单词的频率

java - 当条件诊断关闭时,在 Java 中添加条件诊断是否可以实现零成本?

C++ 将多个字符串更改为一个枚举