我无法在对象数组中查找值,它 returns 我的错误

I cant look for a value in a object array, it returns me error

大家好,我正在做这个音乐播放器,这是歌曲加载器,但问题是当我尝试使用 lookSongbyId 函数将值赋给歌曲常量时,它 returns 我错误 IDK 为什么

let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{


    function lookSongbyId(id)
    {
        queue.forEach(currentSong => {
            if(currentSong.id == id )
            {
                return currentSong
            }   
        })
    }

    const song = lookSongbyId(id)


    console.log(`la canción ${song.name} ha sido cargada`)
}
loadSong(1)

song 常量未定义,我不知道为什么啊啊啊 如果你能帮助我处理这段代码,我将非常感谢你 :DDD

您可以简化您的功能,只使用 find,这将 return 匹配的歌曲。

let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{
    const song = queue.find(x => x.id === id)
    console.log(`la canción ${song.name} ha sido cargada`)
    return song
}
loadSong(1)

如果你想 return 多个项目,你可以直接使用过滤器,或者如果你只想要(如果 id 是唯一的)则查找

const queue = [
      {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
      },
      {
        id: 2,
        name: 'Another Song2',
        artist: 'Favio Figueroa',
      }
    ];
    const useFilter = queue.filter((row) => row.id === 1 );
    console.log('useFilter', useFilter) // [ { id: 1, name: 'Crush', artist: 'Glades' } ]
    const useFind = queue.find((row) => row.id === 2 );
    console.log('useFind', useFind) // { id: 2, name: 'Another Song2', artist: 'Favio Figueroa' }

您可以在函数中添加该逻辑。

假设functionlookSongbyId只是拼写错误(你必须写function lookSongbyId),forEach函数不能用于return一个值,间接地说。 使用 for ... of.find() 检索元素

不要创建歌曲搜索功能,您可以使用查找并无缝地找到合适的歌曲:

const loadSong = (id) => {
    const song = queue.find( sng => sng.id === id);
    console.log(`la canción ${song.name} ha sido cargada`)
}