簡體   English   中英

如何從 Javascript 中的枚舉中獲取隨機值?

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

我正在修補 Phaser 游戲引擎。 我已經想出如何給精靈着色,所以下一步是給它隨機顏色。 我將如何使用枚舉來做到這一點?

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

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

這是我在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
}

您應該首先將對象實例化為數組

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

然后,獲取數組的隨機位置。

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

我今天剛遇到這個問題,並能夠通過此方法獲得隨機值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM