【问题标题】:How to iterate through entries in enumeration from a loop [duplicate]如何从循环中遍历枚举中的条目[重复]
【发布时间】:2021-08-24 12:04:51
【问题描述】:

我在.ts 扩展名的单独文件中创建了下面发布的颜色枚举。我想知道如何在发布的代码中使用或调用for-loop 中的枚举,以便能够迭代抛出它。 换句话说,如何在循环中遍历下面发布的枚举,以便设置ì = 0 RED 以及何时设置i=7 LIME

显然,双问市场将被替换为通过枚举的迭代。

代码

for(let i = 0; i < centerPointsClusters.length;i++) {
            this.centerPoint = this.APIService.visualisePoint(this.map,centerPointsClusters[i], ??)
        }
        

枚举

export enum ColorEnum {
    RED = "#F44336",
    PINK = "#FF4081",
    PURPLE = "#9C27B0",
    INDIGO = "#536DFE",
    BLUE = "#2196F3",
    TEAL = "#64FFDA",
    GREEN = "#4CAF50",
    LIME = "#EEFF41",
    YELLOW = "#FFEB3B",
    ORANGE = "#FFAB40"
  }
  

【问题讨论】:

  • @R.Richards 不,它没有。我想根据循环中 i 的索引遍历枚举

标签: javascript angular


【解决方案1】:

AFAIK,打字稿中的枚举基本上是一个对象。所以你可以获取密钥并遍历它

import { ColorEnum } from './ColorEnum';
const enumKeys = Object.keys(ColorEnum);

for(let i = 0; i < centerPointsClusters.length;i++) {
    this.centerPoint = this.APIService.visualisePoint(this.map, centerPointsClusters[i], enumKeys[i])
}

【讨论】:

  • 我得到这个错误:ERROR TypeError: Cannot convert undefined or null to object
  • @LetsamrIt 我猜你还没有导入枚举。 import ColorEnum from './ColorEnum'
  • 我按照你说的导入了它。现在我得到空数组
  • @LetsamrIt 查看更新的答案,尽管您必须确保枚举文件的文件名和路径正确
【解决方案2】:

也许你可以使用 obj 代替枚举

const obj =  {
RED : "#F44336",
PINK : "#FF4081",
PURPLE : "#9C27B0",
INDIGO : "#536DFE",
BLUE : "#2196F3",
TEAL : "#64FFDA",
GREEN : "#4CAF50",
LIME : "#EEFF41",
YELLOW : "#FFEB3B",
ORANGE : "#FFAB40"
};


const iterateObj = () => {
for(let i in obj) {
    console.log(i, obj[i]);
  }
}

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2012-11-08
    • 2011-09-04
    • 1970-01-01
    • 2011-05-07
    • 2021-04-01
    相关资源
    最近更新 更多