Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)];
like image 497
Shortstuff81000 Avatar asked May 12 '26 07:05

Shortstuff81000


2 Answers

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]];
like image 117
Sinan Ulker Avatar answered May 13 '26 21:05

Sinan Ulker


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
}
like image 30
Muhamet Smaili Avatar answered May 13 '26 21:05

Muhamet Smaili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!