简体   繁体   English

如何使用 integer 作为 Typescript 中的值遍历枚举?

[英]How to iterate through enums with integer as value in Typescript?

I have an enum我有一个枚举

export enums Actions {
All = 1,
Success = 2,
Failed = 3
}

When I iterate through it using for loop, I am getting total of 6 entries.当我使用 for 循环遍历它时,我总共得到 6 个条目。 I get to know that this is how it works in Typescript.我知道这就是它在 Typescript 中的工作方式。 But how can I use the enum so that I can access但是我怎样才能使用枚举以便我可以访问

enum.key 

for "All, Success, Falied" and对于“所有,成功,失败”和

enum.value 

for 1,2,3对于 1,2,3

const keys = Object.keys(Actions);
const values = Object.values(Actions);

What you can do in order to access the enum keys and values like you described in the OP is convert your enum to a basic object that has the properties keys and values with the corresponding data.为了像在 OP 中描述的那样访问枚举keysvalues ,您可以做的是枚举转换为基本的 object,它具有属性keysvalues以及相应的数据。

export enum Actions {
  All = 1,
  Success = 2,
  Failed = 3
}

export type ConvertedActions = {
  keys: string[];
  values: Actions[];
};

const result = Object.values(Actions).reduce(
  (acc, curr): ConvertedActions =>
    isNaN(+curr)
      ? {...acc, keys: [...acc.keys, curr as string]}
      : {...acc, values: [...acc.values, curr as Actions]},
  <ConvertedActions>{keys: [], values: []}
);

console.log(result.keys);    // [ 'All', 'Success', 'Failed' ]
console.log(result.values);  // [ 1, 2, 3 ]

As per the docs of typescript, if as const keyword suffices, then we dont need to use enum.根据 typescript 的文档,如果as const关键字就足够了,那么我们不需要使用枚举。

Just interpreting, maybe in this case an implementation like illustrated can be used, with Object.keys(obj) and Object.values(obj) to get the required outputs只是解释,也许在这种情况下,可以使用如图所示的实现,使用Object.keys(obj)Object.values(obj)来获得所需的输出

const Actions = {
  All: 0,
  Success: 1,
  Failure: 2
} as const

let keyArr = Object.keys(Actions);
let valArr = Object.values(Actions);

What you can do, in this specific case, is separating All, Success, Falied and 1, 2, 3 in two different arrays.在这种特定情况下,您可以做的是在两个不同的 arrays 中分离All, Success, Falied1, 2, 3

export enums Actions {
    All = 1,
    Success = 2,
    Failed = 3
}
console.log(Object.keys(enums).filter((v) => isNaN(Number(v)))); // ["All", "Success", "Failed"] 
console.log(Object.keys(enums).filter((v) => !isNaN(Number(v)))); // ["1", "2", "3"]

You can also do it with a for..in loop:您也可以使用for..in循环来做到这一点:

for (const value in enums) {
  console.log(value); // 1, 2, 3, All, Success, Falied
  console.log(value.filter((v) => isNaN(Number(v)))); // All, Success, Falied
  console.log(value.filter((v) => !isNaN(Number(v)))); // 1, 2, 3
}

There are more ways to do it using forEach , for..of , etc. But from your question I think my example should do the trick.使用forEachfor..of等还有更多方法可以做到这一点。但是从您的问题来看,我认为我的示例应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM