用JavaScript存储和添加歌曲



我想在JavaScript中静态存储10首歌曲,并通过web应用程序动态添加更多歌曲。
同时,我想使用按钮在列表中随机显示5首歌曲。我喜欢搜索框。有人能给点提示吗?

在客户端上有10首歌是坏主意,因为每次加载网页时需要在用户浏览器上加载10首歌。用户可能不会听所有的,而只听1或2。

最好的方法是你有你最好的10首歌列表,一旦用户播放一些歌曲,你立即流式传输。

你可以从git项目中搜索"git: music player"找到示例代码

// Predefined Songs
const songs = [
'song 1',
'song 2',
'song 3',
'song 4',
'song 5',
'song 6',
'song 7',
'song 8',
'song 10',
];
// Parent Element of list of songs
const ul = document.querySelector('ul');
// Add Songs
songs.push('song');
// Display It
const displaySongs = () => {
const randomSongs = [];
for (let i = 0; i < 5; i++) {
let songIndex = Math.floor(Math.random() * songs.length);
if (!randomSongs.includes(songs[songIndex])) {
randomSongs.push(songs[songIndex]);
} else {
i--;
}
}
ul.innerHTML = randomSongs.map((song) => `<li>${song}</li>`).join('');
};
displaySongs();

最新更新