【问题标题】:How to filter list elements from enum in typescript?如何从打字稿中的枚举中过滤列表元素?
【发布时间】:2018-05-16 15:34:45
【问题描述】:

我正在使用 Typescript 开发 Angular 2,并且我有一个场景,我必须在与枚举比较后从列表中过滤元素。喜欢-

let products: Array<IProduct> = [A, B, C, D, E, F];

下面是我的枚举-

    export const enum ProductType {
        A= 0,
        B= 1,
        C= 2       
   }

现在我想在检查枚举后返回一个包含以下元素的列表-

let filteredProductList: Array<IProduct> = [A, B, C];

目前我正在通过 switch case 执行此操作,但我想要一些适当的解决方案。任何建议将不胜感激。

【问题讨论】:

    标签: angular typescript enums filtering


    【解决方案1】:

    Enum 中删除 conts 并像这样访问枚举 ProductType['C']

    枚举

    export enum ProductType {
            A= 0,
            B= 1,
            C= 2       
    }
    

    示例

    products.forEach(element => {
       let valueInEnum = ProductType[element]; 
       console.log("valueInEnum = "+ valueInEnum);
    });
    

    【讨论】:

    • 它给了我一个错误,“元素”不能在下面的行中使用索引 let valueInEnum = ProductType[element];
    • note 从枚举中删除 const。这个想法是从数组 products 中获取值,并且该值将其用作枚举中的索引,例如 ProductType[“C”]
    • 你收到了吗?
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2020-01-29
    • 2020-05-04
    • 2017-03-06
    相关资源
    最近更新 更多