[英]How can I use enum values as index of array
我嘗試使用枚舉值作為數組的索引,但它給了我一個錯誤。
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轉換為數字,但它不起作用。
有什么辦法可以將Enum值用作索引嗎?
要創建枚舉,我們創建一個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)
試試這個。
let color = {
RED : 0,
BLUE : 1,
GREEN : 2
}
module.exports = color
let x = ['warning', 'info', 'success'];
let anotherVariable = x[color.RED];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.