简体   繁体   English

减少内部函数返回未定义(?)

[英]reduce inside function returns undefined (?)

in this sample using reduce on array of objects works fine but when i insert it all into a function it starts to return undefined... it probably has to do with me not understanding how returning stuff from functions works在这个示例中,在对象数组上使用 reduce 工作正常,但是当我将其全部插入到一个函数中时,它开始返回 undefined ... 这可能与我不了解从函数返回的东西是如何工作的有关

 const egArrOfObj = [ { name:'tomato', }, { name:'potato', }, ]; console.log( egArrOfObj .reduce((acc, curr) => { return [...acc, curr.name] } ,[] ) ); const namesFunction = (arrOfObj) => { arrOfObj .reduce((acc, curr) => { return [...acc, curr.name] } ,[] ) }; const names = namesFunction(egArrOfObj); console.log(names)

If you add the return statement into your function then it will work as well.如果您将return语句添加到您的函数中,那么它也会起作用。

Like the following:像下面这样:

 const egArrOfObj = [{ name:'tomato', }, { name:'potato', }]; const namesFunction = (arrOfObj) => { return arrOfObj.reduce((acc, curr) => { return [...acc, curr.name] }, []) }; console.log(namesFunction(egArrOfObj));

I hope that helps!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM