简体   繁体   English

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

[英]How to choose a random Value from Assoc array then display the key and value

Hello I am trying to display a random value key pair separately in a string. 您好,我试图在字符串中分别显示一个随机值键对。 I want the value and key to remain together. 我希望值和键保持在一起。

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
     };

Want this but for assoc array 想要这个但是对于assoc数组

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

Example Code Wanted 想要的示例代码

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

Wanted Output 想要的输出

charizard used flamethrower and did 12 damage! 喷火器使用喷火器造成了12点伤害!

Thanks in advance! 提前致谢!

You can use Object.keys() to get a array filled with the object property names. 您可以使用Object.keys()获得一个由对象属性名称填充的数组。 So, applying a random index on that array, you can get a random property name, then you can use it to get the random property value desired. 因此,在该数组上应用随机索引,可以获得一个随机属性名称,然后可以使用它来获取所需的随机属性值。

  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]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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