我想設定我必須從陣列中獲取的不和諧機器人的活動隨機播放訊息。我已經測驗了這段代碼,但它只會顯示陣列中的最后一個,或者有時只顯示第一個和最后一個:
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'
}
]
謝謝你的幫助。
uj5u.com熱心網友回復:
有兩種方法可以做到這一點:要么在每個間隔從陣列中選擇一個隨機元素,要么回圈遍歷所有元素,一旦所有元素都完成,然后重新開始:
- 方法1:要做到這一點,您只需在
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);
- 方法 2:對于這種方法,您必須在
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);
uj5u.com熱心網友回復:
試試這個代碼:
{
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)
uj5u.com熱心網友回復:
您不必使用aa變數,只需這樣做:
setInterval(() => {
const presence = array[Math.floor(Math.random() * array.length)];
client.user.setActivity(presence.type, { type: "PLAYING });
}, 10000);
別忘了這會回傳一個隨機型別,你可以連續取 4 個 ejx1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487528.html
標籤:javascript 数组 不和谐.js 地位
上一篇:將滑塊變數發送到php
