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
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!
Thanks in advance!
You can use Object.keys()
to get a array filled with the object property names. 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]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.