gpt4 book ai didi

javascript - 如何使用 Javascript 从 JSON 文件中选择一个随机对象(?)?

转载 作者:搜寻专家 更新时间:2023-11-01 00:28:12 25 4
gpt4 key购买 nike

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

// ...

关于javascript - 如何使用 Javascript 从 JSON 文件中选择一个随机对象(?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com