简体   繁体   中英

How do I get a random value from enums in Javascript?

I am tinkering with Phaser game engine. I have figured out how to color the sprite, so the next step is giving it a random color. How would I do that using an enum?

var colors = {
    RED: 0xff0000,
    GREEN: 0x00ff00,
    BLUE: 0x0000ff
}

logo.tint = colors[Math.floor(Math.random() * colors.length)];

Here is a method I wrote in typescript that I used, remove types if you want to use with javascript.

function getRandomEnumValue<T>(anEnum: T): T[keyof T] {
  //save enums inside array
  const enumValues = Object.keys(anEnum) as Array<keyof T>; 
  
  //Generate a random index (max is array length)
  const randomIndex = Math.floor(Math.random() * enumValues.length);
  // get the random enum value
  
  const randomEnumKey = enumValues[randomIndex];
  return anEnum[randomEnumKey]; 
 // if you want to have the key than return randomEnumKey
}

You should first instance your object as a Array

var colors =[
    {RED: 0xff0000},
    {GREEN: 0x00ff00},
    {BLUE: 0x0000ff}
];

Then, get a random position of the array.

colors[Math.floor(Math.random() * colors.length)];

I just came to this problem today and able to get a random value by this:

var rand = Math.floor(Math.random() * Object.keys(colors).length);
var randColorValue = colors[Object.keys(colors)[rand]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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