在我正在制作的 Discord Bot 中,它需要从 JSON 文件中选择一个随机对象。我当前的代码是这样的:
function spawn(){
if (randomNum === 24) return
const name = names.randomNum
const embed = new Discord.RichEmbed()
.setTitle(`${name} has been found!`)
.setColor(0x00AE86)
.setThumbnail(`attachment://./sprites/${randomNum}.png`)
.setTimestamp()
.addField("Quick! Capture it with `>capture`!")
msg.channel.send({embed});
}
JSON 文件如下所示:
{
"311": "Blargon",
"310": "Xryzoz",
"303": "Noot",
"279": "",
"312": "Arragn",
"35": "Qeud",
...
}
我希望它随机选择其中一个,例如303
,并将其发布到丰富的嵌入中。从这里我该怎么办?
您可以选择一个随机名称,如下所示:
// Create array of object keys, ["311", "310", ...]
const keys = Object.keys(names)
// Generate random index based on number of keys
const randIndex = Math.floor(Math.random() * keys.length)
// Select a key from the array of keys using the random index
const randKey = keys[randIndex]
// Use the key to get the corresponding name from the "names" object
const name = names[randKey]
// ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)