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

问题描述

大家好,我正在做这个音乐播放器,这是歌曲加载器,但问题是当我尝试使用 lookSongbyId 函数将值分配给歌曲常量时,它会返回一个错误 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

解决方法

如果你想返回多个项目,你可以直接使用过滤器,或者如果你只想找到(如果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,artist: 'Glades' } ]
    const useFind = queue.find((row) => row.id === 2 );
    console.log('useFind',useFind) // { id: 2,artist: 'Favio Figueroa' }

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

,

您可以简化您的函数,只使用 find 将返回匹配的歌曲。

let queue = [
    {
        id: 1,}
]

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)
,

假设 functionlookSongbyId 只是拼写错误(你必须写 function lookSongbyId),forEach 函数不能用于返回值,如间接所说的 here。 使用 for ... of.find() 检索元素

,

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

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