![](/img/trans.png)
[英]how to display a random value from an array of objects in an React view
[英]How to choose a random Value from Assoc array then display the key and value
您好,我試圖在字符串中分別顯示一個隨機值鍵對。 我希望值和鍵保持在一起。
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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.