如何在JavaScript中从枚举中获取随机值?

9

我正在尝试使用Phaser游戏引擎。我已经弄清如何给精灵上色,下一步是随机给它一个颜色。我该如何使用枚举来实现这个目标?

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

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

3
logo.tint=colors[Math.floor(Math.random() * Object.keys(colors).length)] - dandavis
颜色[Math.random() % Object.keys(颜色).length)] - subdigit
@subdigit:遗憾的是,我认为它不能做到你想要的,而且我知道它也不能满足原帖作者的需求... - dandavis
哈哈,没错。随机数是0到1吧... - subdigit
如何将颜色存储在数组中并使用**game.rnd.weightedPick(myColorArray)**随机选取? - Shohanur Rahaman
3个回答

12

今天我遇到了这个问题,通过以下方式能够获取一个随机值:

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

3

这是我用typescript编写的一个方法,如果你想在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
}

1
你应该首先将对象实例化为一个数组。
var colors =[
    {RED: 0xff0000},
    {GREEN: 0x00ff00},
    {BLUE: 0x0000ff}
];

然后,获取数组的随机位置。
colors[Math.floor(Math.random() * colors.length)];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接