您好,我正在尝试在字符串中单独显示随机值 key 对。我希望值和键保持在一起。
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
};
想要这个但用于关联数组
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]);
关于javascript - 如何从 Assoc 数组中选择一个随机值然后显示键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27538667/