JavaScript将歌曲数组按艺术家分组时首个元素遗漏问题排查
问题原因
你的代码核心逻辑漏洞是:当检测到当前歌曲所属艺术家和artistIndex指向的艺术家不匹配、执行artistIndex +=1切换到下一位艺术家后,没有将触发这次索引切换的、属于新艺术家的当前歌曲插入到对应数组中,所以除了第一位艺术家外,其他所有艺术家的第一首歌都会被跳过。另外原代码没有给变量加let/const声明,容易产生全局作用域污染问题。
修复方案
方案1:在原有逻辑基础上调整,补充切换索引后的插入逻辑
let artistIndex = 0 const tempPlaylist = [ '1 - a', '2 - a', '2 - a', '3 - a', '3 - b', '3 - c', '4 - a', '5 - a', '5 - b', '6 - a', ] const artistsNested = [ ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ] for (let song of tempPlaylist) { const artistSongSplit = song.split(' - '); const artistName = artistSongSplit[0]; const songName = artistSongSplit[1]; if (artistName.toUpperCase() === artistsNested[artistIndex][0].toUpperCase()) { artistsNested[artistIndex].push(songName) } else { artistIndex += 1 // 切换索引后插入当前属于新艺术家的歌曲 artistsNested[artistIndex].push(songName) } } console.log(artistsNested)
方案2:更稳妥的匹配逻辑,无需手动维护索引
如果不能保证歌单里的歌曲是严格按艺术家顺序排列的,可以直接根据艺术家名称匹配对应数组,避免匹配出错:
const tempPlaylist = [ '1 - a', '2 - a', '2 - a', '3 - a', '3 - b', '3 - c', '4 - a', '5 - a', '5 - b', '6 - a', ] const artistsNested = [ ['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ] for (let song of tempPlaylist) { const [artistName, songName] = song.split(' - '); // 直接查找对应艺术家的数组 const targetArtist = artistsNested.find(item => item[0].toUpperCase() === artistName.toUpperCase()) if (targetArtist) targetArtist.push(songName) } console.log(artistsNested)
两种方案运行后最终输出结果都符合预期:
[ ['1', 'a'], ['2', 'a', 'a'], ['3', 'a', 'b', 'c'], ['4', 'a'], ['5', 'a', 'b'], ['6', 'a'] ]
内容的提问来源于stack exchange,提问作者vvhitearmor
相关产品推荐
相关产品推荐

