减少输出未定义,而它可能不应该

时间:2018-03-24 17:16:19

标签: javascript

这就是问题,当我运行此代码时,它运行正常:

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

但是,当我尝试这个时,输出未定义......我无法弄清楚原因。



undefined




它应该输出一个带有名字的对象,而是我得到\b

我在这里缺少什么? :/

3 个答案:

答案 0 :(得分:2)

缺少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"))

如果您只想要名字,可以更轻松地完成:

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"));

答案 1 :(得分:0)

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

您需要返回reduce函数才能获得结果。

答案 2 :(得分:0)

以下代码示例修复了问题并进行了评论。

您从中获取代码的函数还有另一个问题 - 您的数据结构不适合从中创建对象,因为对象最多只能有一个同名属性。

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