我尝试使用枚举值作为数组的索引,但它给我一个错误。
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)
关于javascript - 如何使用枚举值作为数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930230/