为什么这个函数总是返回 null

Son*_*ony 0 javascript foreach

这是我的 JavaScript 函数,用于检查数组中是否存在特定条目,但即使存在匹配项,它也始终返回 null

function getSupplierForId(supplierId) {                               
    data.suppliers.forEach(x => {                                     
        console.log('Current item id : ' + x.id);                     
        console.log('Requested supplier id : ' + supplierId);         
        console.log('Both ids are equal : ' + (x.id === supplierId)); 
        if (x.id === supplierId) {                                    
            console.log(x);                                           
            return x;                                                 
        }                        
    });                                                               
    return null;                                                      
}                                                                     
Run Code Online (Sandbox Code Playgroud)

这是我的控制台输出:

控制台输出

为什么它总是返回 null?

Fel*_*ing 5

因为你return null;到了最后。return语句不跨越函数边界。return x;仅从内部函数(其调用者是.forEach)返回,而不是从外部函数返回。

无论如何,在您的情况下使用的正确工具是.find

function getSupplierForId(supplierId) {                               
  return data.suppliers.find(x => x.id === supplierId)  
}    
Run Code Online (Sandbox Code Playgroud)

您可能还会发现我关于回调的帖子很有趣:https : //felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html