简体   繁体   English

JS Array Reduce 的好奇反应

[英]Curious Response of JS Array Reduce

Been using JS reduce on arrays and I stumbled on this weird undefined response when I used it on an object.一直在 arrays 上使用 JS reduce,当我在 object 上使用它时,我偶然发现了这个奇怪的未定义响应。

Here is the input:这是输入:

var desks = [
  { type: "sitting" },
  { type: "standing" },
  { type: "sitting" },
  { type: "sitting" },
  { type: "standing" },
];

and here is the function that am trying to run this input on:这里是 function 试图运行这个输入:

const deskCount = (desks) => {
  desks.reduce(
    (count, thisdesk) => {
      if (thisdesk.type == "sitting") count.sitting = count.sitting + 1;
      if (thisdesk.type == "standing") count.standing = count.standing + 1;
      console.log(count); //this line is logging correctly but function returns undefined
      return count;
    },
    { sitting: 0, standing: 0 }
  );
};

Running it using Node 12.18.0 and wrapped with babel.使用 Node 12.18.0 运行它并用 babel 包装。

The issue is that you have used a multi-line arrow function without returning a value.问题是您使用了多线箭头 function 而没有返回值。 The inner reduce runs fine, however, the wrapping code does not return anything when it is inside of {} .内部reduce运行良好,但是,包装代码在{}内部时不返回任何内容。

Either use return for the wrapping {} , or omit the {} .使用 return 包装{} ,或省略{} I think omitting is best.我认为省略是最好的。

const deskCount = (desks) =>
  desks.reduce(
    (count, thisdesk) => {
      if (thisdesk.type == "sitting") count.sitting = count.sitting + 1;
      if (thisdesk.type == "standing") count.standing = count.standing + 1;
      console.log(count); //this line is logging correctly but function returns undefined
      return count;
    },
    { sitting: 0, standing: 0 }
  );

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

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