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]);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다