[英]How can set a shuffle status with array in discord.js (javascript)
我想设置我必须从数组中获取的不和谐机器人的活动随机播放消息。 我已经测试了这段代码,但它只会显示数组中的最后一个,或者有时只显示第一个和最后一个:
const array = [
{
id: '08933438391',
type: 'ejx1'
},
{
id: '12361425430',
type: 'ejx3'
},
{
id: '63746455430',
type: 'ejx2'
},
{
id: '83972535430',
type: 'ejx4'
}
]
setInterval(() => {
const aa = [
{ type: 'PLAYING', message: array.type }
];
const presence = aa[Math.floor(Math.random() * aa.length)];
client.user.setActivity(presence.message, { type: presence.type });
}, 10000);
这是我的数组:
[
{
id: '08933438391',
type: 'ejx1'
},
{
id: '12361425430',
type: 'ejx3'
},
{
id: '63746455430',
type: 'ejx2'
},
{
id: '83972535430',
type: 'ejx4'
}
]
谢谢你的帮助。
试试这个代码:
{
id: '08933438391',
type: 'ejx1'
},
{
id: '12361425430',
type: 'ejx3'
},
{
id: '63746455430',
type: 'ejx2'
},
{
id: '83972535430',
type: 'ejx4'
}
]
setInterval(() => {
const aa = [
{ type: 'PLAYING', message: messageArray[0].type }
]
const presence = messageArray[Math.floor(Math.random() * messageArray.length)]
client.user.setActivity(presence.message, { type: presence.type })
}, 10000)
您不必使用aa
变量,只需这样做:
setInterval(() => {
const presence = array[Math.floor(Math.random() * array.length)];
client.user.setActivity(presence.type, { type: "PLAYING });
}, 10000);
别忘了这会返回一个随机类型,你可以连续取 4 个 ejx1
有两种方法可以做到这一点:要么在每个间隔从数组中选择一个随机元素,要么循环遍历所有元素,一旦所有元素都完成,然后重新开始:
setInterval()
函数中添加一个随机元素生成器,以从数组中选择一个随机元素,然后您可以使用以下方法应用它:setInterval(() => {
const randomElement = array[Math.floor(Math.random() * array.length)];
const aa = [
{
type: 'PLAYING',
message: randomElement.type
}
];
client.user.setActivity(aa.message, { type: aa.type });
}, 10000);
setInterval()
函数之外保留一个计数器,然后在每次函数运行时递增它。 一旦计数器达到某个数字,则将其重置回 0。例如:let counter = 0
setInterval(() => {
const aa = [
{
type: 'PLAYING',
message: array[counter].type
}
];
client.user.setActivity(aa.message, { type: aa.type });
counter++;
counter = counter === array.length - 1 ? 0 : counter
}, 10000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.