Javascript 检查数组,查看它是否在移位后立即为空
所以我在我的音乐机器人上取得了进步。目前,它洗牌播放列表,播放列表中的每首歌曲一次。下一步是让他在播放完每首歌曲后重新洗牌播放列表,然后再继续播放(稍后我会用命令捕捉“阻止”他)。从理论上讲,我所要做的就是加上一个检查“如果数组包含0位置的条目,播放下一首歌”,否则“如果数组为空,再次洗牌播放列表,然后播放下一首歌” 不幸的是,即使下一首歌未定义-检查失败,在播放列表第一次运行之后,他开始滥发未定义的歌曲。我尝试了多种方法来检查这一点。检查数组中的条目是否未定义,检查数组的长度是否未定义,检查条目是否包含在原始歌曲列表中-所有歌曲都存在相同的问题Javascript 检查数组,查看它是否在移位后立即为空,javascript,arrays,discord,Javascript,Arrays,Discord,所以我在我的音乐机器人上取得了进步。目前,它洗牌播放列表,播放列表中的每首歌曲一次。下一步是让他在播放完每首歌曲后重新洗牌播放列表,然后再继续播放(稍后我会用命令捕捉“阻止”他)。从理论上讲,我所要做的就是加上一个检查“如果数组包含0位置的条目,播放下一首歌”,否则“如果数组为空,再次洗牌播放列表,然后播放下一首歌” 不幸的是,即使下一首歌未定义-检查失败,在播放列表第一次运行之后,他开始滥发未定义的歌曲。我尝试了多种方法来检查这一点。检查数组中的条目是否未定义,检查数组的长度是否未定义,检查条
function PlaySong(connection, channel, SongToPlay) {
console.log('Now playing '+SongToPlay[0]+'.'); //announce the song
message.channel.send('Now playing '+SongToPlay[0]+'.');
const dispatcher = connection.play('./Scythe Digital Edition - Soundtrack/'+SongToPlay[0]+'.mp3'); //play the song
dispatcher.setVolume(0.1); //at this volume
dispatcher.on("finish", () => { //when the song concludes
SongToPlay.shift(); //remove that song from the list of songs to play
if (!isNullOrUndefined(SongToPlay[0]) || SongToPlay[0] !== '') { //if the list of songs is not empty
PlaySong(connection, channel, SongToPlay); //repeat the above for the next song
}
else { //otherwise if it was empty
SongToPlay = shuffle(testbells); //shuffle the playlist and repopulate the list of songs to play
PlaySong(connection, channel, SongToPlay); //then repeat the above for the next song
//channel.leave();
//return;
}
});
}
没有看到所有代码有点困难,所以我制作了一个简单的版本,它应该适合-它只是打印,而不是播放任何东西或消息,但这应该是一个合理的结构为您
//define your starting song array
let originalSongArray = ["Abba","Beatles","ACDC","Britney","Elvis"];
//create a shuffled version of that array
let shuffledArray = originalSongArray.slice();
shuffle(shuffledArray);
//set the number of songs you want to play
//note how the number is higher than the array of available songs causing shuffles
let songsToPlay = 12;
while (songsToPlay > 0)
{
//"play" the song (in this case write to console)
console.log("Playing song from, " + shuffledArray[0]);
//"remove the song from the shuffled list
shuffledArray.shift();
//test to ensure there are still songs remaining
if(shuffledArray.length == 0){
//regenerate a new shuffled list from the original
//note, we never altered the original list order or content
shuffledArray = originalSongArray.slice();
shuffle(shuffledArray);
}
//reduce number of songs to play
songsToPlay--;
}
一个简单的洗牌函数引用了这个问题:
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}