如何从 Assoc 数组中选择随机值,然后显示键和值



您好,我正在尝试在字符串中单独显示随机值键对。我希望价值和密钥保持在一起。

charAT = {
         'Flamethrower' : Math.floor(Math.random()*(15-5+1)+5),
         'Headbut' : Math.floor(Math.random()*(5-3+1)+3),
         'Fireblast' : Math.floor(Math.random()*(25-10+1)+10),
         'Tailwhip': 0
     };

想要这个,但对于 assoc 数组

rand = charAT[Math.floor(Math.random() * charAT.length)];

需要的示例代码

alert('charizard used '+ rand:key + 'and did ' + rand:value + ' damage!')

想要的输出

喷火龙使用火焰喷射器并造成 12 点伤害!

提前感谢!

您可以使用

Object.keys()来获取填充对象属性名称的数组。因此,在该数组上应用随机索引,您可以获得一个随机属性名称,然后您可以使用它来获取所需的随机属性值。

 var charAT = {
     'Flamethrower' : Math.floor(Math.random()*(15-5+1)+5),
     'Headbut' : Math.floor(Math.random()*(5-3+1)+3),
     'Fireblast' : Math.floor(Math.random()*(25-10+1)+10),
     'Tailwhip': 0
 };
 var ix = Math.floor(Math.random() * Object.keys(charAT).length);
 var rand = Object.keys(charAT)[ix];
 alert(rand + ":" + charAT[rand]);

最新更新