English 中文(简体)
• 如何在字典中随机 en?
原标题:How to get a random enum in TypeScript?

如何从列举中获取随机物品?

enum Colors {
  Red, Green, Blue
}

function getRandomColor(): Color {
  // return a random Color (Red, Green, Blue) here
}
最佳回答

genericmeth,该方法可回收esafe arbitrary enum

function randomEnum<T>(anEnum: T extends object): T[keyof T] {
  const enumValues = Object.keys(anEnum)
    .map(n => Number.parseInt(n))
    .filter(n => !Number.isNaN(n)) as unknown as T[keyof T][]
  const randomIndex = Math.floor(Math.random() * enumValues.length)
  const randomEnumValue = enumValues[randomIndex]
  return randomEnumValue;
}

如此:

interface MyEnum {X, Y, Z}
const myRandomValue = randomEnum(MyEnum) 

www.un.org/spanish/ga 数值为<代码>MyEnum。

问题回答

上述多数答复是回到顶点上来的,但是我们并没有真正关心 en的价值?

If you are using lodash, this is actually as simple as:

_.sample(Object.values(MyEnum))

如果你不使用 lo子,或者你想把它当作自己的功能,我们仍可以通过修改@Steven Spungin的回答来获得一种类型的安全随机 en,以便:

function randomEnum<T>(anEnum: T): T[keyof T] {
  const enumValues = (Object.values(anEnum) as unknown) as T[keyof T][];
  const randomIndex = Math.floor(Math.random() * enumValues.length);
  return enumValues[randomIndex];
}

因此,我对我没有做任何回答。

内容提要

export enum Jokenpo {
  PAPER =  PAPER ,
  ROCK =  ROCK ,
  SCISSOR =  SCISSOR ,
}

选择

const index= Math.floor(Math.random() * Object.keys(Jokenpo).length);
const value= Object.values(Jokenpo)[index];

return Jokenpo[value];

我只想从 en中抽取随机值,然后将其转换成实事。

这是我可以讨论的最佳办法,但它看上去像一个黑板,取决于在字典中执行<代码>enum,而我确信,这并不保证保持同样。

举例说

enum Color { Red, Green, Blue }

如果我们的<代码>console.log,我们就会获得以下产出。

{
   0 :  Red ,
   1 :  Green ,
   2 :  Blue ,
  Red: 0,
  Green: 1,
  Blue: 2,
}

这意味着,我们可以走到这个目标的关键位置上,只用数字价值,例如:

const enumValues = Object.keys(Color)
  .map(n => Number.parseInt(n))
  .filter(n => !Number.isNaN(n))

就我们而言,enumValues现为[0, 1, 2]。 我们现在只能随机抽取其中一部分。 很好地履行了以下职能:,这正是我们随机选择指数所需要的。

const randomIndex = getRandomInt(0, enumValues.length)

现在,我们只是拿到随机列举的价值:

const randomEnumValue = enumValues[randomIndex]

EDIT: Fixed type issue.

Tidying up @Shailendra 如果 en体被界定为问题,而没有任何习俗指数,那么,这是一种简单的做法:

enum Color {
  Red, Green, Blue
}
  
function getRandomColor(): Color {
  var key = Math.floor(Math.random() * Object.keys(Color).length / 2);
  return Color[key];
}

请注意,此处(按有关要求)的返回类型<代码>Color实际上是总指数,而不是一个肤色名称。

除@sarink的答复外。

import _ from  lodash ;

export function getRandomValueFromEnum<E>(enumeration: { [s: string]: E } | ArrayLike<E>): E {
  return _.sample(Object.values(enumeration)) as E;
}

你们可以找到以下标准来做事。

enum Colors {
  Red,
  blue,
  pink,
  yellow,
  Orange
}

function getRandomColor(): string {
  // returns the length
  const len = (Object.keys(Colors).length / 2) - 1;
  // calculate random number
  const item = (Math.floor(Math.random() * len) + 0);

  return Colors[item];
}

If you are using the faker package (I use it for tests), you can use the following. This solution utilizes the arrayElement function to pick a random color from the Colors enum.

// Get an array of all values in the Colors enum
const colorValues = Object.values(Colors);

// Use arrayElement from faker to pick a random color from the array
const randomColor = faker.helpers.arrayElement(colorValues);

在ES5中为我工作的解决办法是:

function getRandomEnum<T extends object>(anEnum: T): T[keyof T] {
  const enumValues = Object.keys(anEnum)
    .filter(key => typeof anEnum[key as keyof typeof anEnum] ===  number )
    .map(key => key);
 
  const randomIndex = Math.floor(Math.random() * enumValues.length)
  
  return anEnum[randomIndex as keyof T];
}

这不是完美的,而是可以尝试这样的东西。

function getRandomEnum(input: object): any {
  const inputTransform: { [key: string]: string } = input as { [key: string]: string };
  const keysToArray = Object.keys(inputTransform);
  const valuesToArray = keysToArray.map(key => inputTransform[key]);

  if (!isNaN(parseInt(keysToArray[0], 10))) {
    const len = keysToArray.length;

    while (keysToArray.length !== len / 2) {
      keysToArray.shift();
      valuesToArray.shift();
    }
  }

  const randIndex = Math.floor(keysToArray.length * Math.random());

  return valuesToArray[randIndex];
}

......

enum Names {
  foo,
  bar,
  baz,
  // foo = "fooZZZ",
  // bar = "barZZZ",
  // baz = "bazZZZ",
}

for (let i = 0; i < 10; i += 1) {
  const result = getRandomEnum(Names);
  if (result === Names.foo) console.log(`${result} is foo`);
  else if (result === Names.bar) console.log(`${result} is bar`);
  else if (result === Names.baz) console.log(`${result} is baz`);
}

产出

0 is foo
0 is foo
2 is baz
0 is foo
2 is baz
2 is baz
1 is bar
1 is bar
2 is baz
1 is bar

......

bazZZZ is baz
bazZZZ is baz
bazZZZ is baz
barZZZ is bar
bazZZZ is baz
barZZZ is bar
barZZZ is bar
fooZZZ is foo
barZZZ is bar
fooZZZ is foo
enum Colors {
  Red, Green, Blue
}

const keys = Object.keys(Colors)
const real_keys = keys.slice(keys.length / 2,keys.length)
const random =  real_keys[Math.floor(Math.random()*real_keys.length)]
console.log(random)

采用ESNext对3.5.2型号进行测试。 这非常简单。

使用名称空间

enum Colors {
  Red,
  Green,
  Blue,
}
namespace Colors {
  // You need to minus the function inside your namespace
  // That s why I had - 1
  // Because instead of 0,1,2,red,green,blue = 6
  // It will be 0,1,2,red,green,blue,Random = 7
  export function Random(): any {
    const length = ((Object.keys(Colors).length - 1) / 2)
    return Colors[Math.floor(Math.random() * length / 2)]
  }
}

console.log(Colors.Random())

涉及所有类型问题的解决方案

function randomEnum<T extends Record<string, number | string>>(anEnum: T): T[keyof T] {
  const enumValues = getEnumValues(anEnum);
  const randomIndex = Math.floor(Math.random() * enumValues.length);
        
  return enumValues[randomIndex];
}

Used lodash,但功能可以在没有功能的情况下重写。

function getEnumValues<T extends Record<string, number | string>>(anEnum: T): Array<T[keyof T]> {
  const enumClone = _.clone(anEnum);

  _.forEach(enumClone, (_value: number | string, key: string) => {
      if (!isNaN(Number(key))) {
        delete enumClone[key];
      }
    });

  return _.values(enumClone) as Array<T[keyof T]>;
}

enum Status { active, pending }
enum Type { active =  active , pending =  pending  } 
enum Mixed { active =  active , pending = 1 }

randomEnum(Status) // (Return random between 0,1) 
randomEnum(Type) // (Return  active  or  pending  string) 
randomEnum(Mixed) // (Return  active  or 1)

一种基于“Steven Spungin”的解决方案,并绕过不必要的过滤:

function randomEnum<T>(anEnum: T): T[keyof T] {
    const enumValues = Object.keys(anEnum) as T[keyof T][];
    const randomIndex = Math.floor(Math.random() * enumValues.length / 2);
    return enumValues[randomIndex];
}

这是我的工作。

enum Colors {
  Red =  Red , 
  Green =  Green , 
  Blue =  Blue ,
};

function getRandomInt(min: number, max: number) {
  return Math.floor(Math.random() * max) + min;
}

const colorKeys = Object.keys(Colors) as (keyof typeof Colors)[];

const randomColor = Colors[
  colorKeys[
    getRandomInt(0, colorKeys.length)
  ]
];




相关问题
Finding the Highest Value in an Enumeration

I m writing a method which determines the highest value in a .NET enumeration so I can create a BitArray with one bit for each enum value: pressedKeys = new BitArray(highestValueInEnum<Keys>());...

Conversion of Enum to Enumerable

To convert Enum to Enumerable ,I use public enum Flags { Trivial=1, Minor, Major, Critical } IEnumerable<int> n = Enumerable.Range((int)Flags.Trivial, (...

Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

Enum scoping issues

I try to keep things as local as possible, so I put enums at class scope, even if they are shared between two classes (I put it in the class that "goes better" with it.) This has worked out great, but ...

How do I sort enum members alphabetically in Java?

I have an enum class like the following: public enum Letter { OMEGA_LETTER("Omega"), GAMMA_LETTER("Gamma"), BETA_LETTER("Beta"), ALPHA_LETTER("Alpha"), private final String ...

C++ enum value initialization

I have an enum declared in my code as: enum REMOTE_CONN { REMOTE_CONN_DEFAULT = 0, REMOTE_CONN_EX_MAN = 10000, REMOTE_CONN_SD_ANNOUNCE, REMOTE_CONN_SD_IO, REMOTE_CONN_AL, ...

WCF: Enforce equal DataContracts on both sides

I m wondering if it is possible to have WCF make sure that the DataContracts on both sides of a connection are exactly the same (and throw an exception when trying to connect if they are not). For ...

热门标签