简体   繁体   English

减少输出undefined,但可能不应该

[英]reduce output undefined while it probably shouldn't

Here's the thing, when I ran this code, it works fine: 事情就是这样,当我运行这段代码时,它可以正常工作:

var arr = [1,2,3,4];
arr.reduce(function(acc,val){
    if(val >= 2){
        acc['the key num ' + val + ' is'] = val;
    } 
    return acc;
},{});

But, when I try this one, it output undefined... I can't figure it out why. 但是,当我尝试这一步时,它的输出未定义...我不知道为什么。

 function ext(arr, zname) { arr.reduce(function(acc, val) { if (val[zname]) { acc = val[zname]; } return acc; }, {}); } console.log(ext([{ name: "Alex", isTeacher: true }, { name: "Bob", isTeacher: true }, { name: "David", isTeacher: true }], "name")) 

It should output an object with the names, but instead I'm getting undefined 它应该输出带有名称的对象,但是相反,我undefined

What am I missing here? 我在这里想念什么? :/ :/

Missing a return statement: 缺少return声明:

 function ext(arr, zname) { // | // V return arr.reduce(function(acc, val) { if (val[zname]) { acc.push(val[zname]); } return acc; }, []); } console.log(ext([{ name: "Alex", isTeacher: true }, { name: "Bob", isTeacher: true }, { name: "David", isTeacher: true }], "name")) 


If you just want the names, that can be done more easily: 如果您只想要名称,则可以更轻松地完成操作:

 const data = [{ name: "Alex", isTeacher: true }, { name: "Bob", isTeacher: true }, { name: "David", isTeacher: true }]; const ext = (arr, v) => arr.map(x => x[v]); console.log(ext(data, "name")); 

 const ext = (arr, zname) => { // Note: the use of `return` below return arr.reduce((acc, val) => { if (val[zname]) { acc = val[zname]; } return acc; }, {}); } console.log(ext([{ name: "Alex", isTeacher: true }, { name: "Bob", isTeacher: true }, { name: "David", isTeacher: true }], "name")) 

You need to return the reduce function to get your result. 您需要返回reduce函数以获得结果。

The issues are fixed and commented in below code example. 在下面的代码示例中,问题已得到修复和评论。

You have another issue with the function you grabbed the code from - your data structure is not suited to create an object from it because an object can only have a maximum of one same-name property. 从中获取代码的函数还有另一个问题-您的数据结构不适合从中创建对象,因为一个对象最多只能具有一个同名属性。

 function ext(arr, zname) { // you need to return the result of arr.reduce return arr.reduce(function(acc, val) { if (val[zname]) { // if you want a list of names, just push the names in acc acc.push(val[zname]); } return acc; // in that case initialize acc with [] instead of {} }, []); } console.log(ext([{ name: "Alex", isTeacher: true }, { name: "Bob", isTeacher: true }, { name: "David", isTeacher: true }], "name")) 

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

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