在我正在制作的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]
// ...