如何满足lint规则'array-callback-return'?

How to satisfy the lint rules 'array-callback-return'?

这是我的第一次剪辑:

const planLimits = {plan1: {condition1: 50, ...}}

function initialisePlanLimits(planLimits) {
  const limits = new Map();
  Object.keys(planLimits).map((planId) => (
    const limitMap = new Map(Object.entries(planLimits[planId]));
    limits.set(planId, limitMap);
  ));
  return limits;
}

linter 标记此错误:error Expected to return a value in this function array-callback-return

所以我改成了这个版本:

function initialisePlanLimits(planLimits) {
  const limits = new Map();
  Object.keys(planLimits).map((planId) => (
    limits.set(planId, new Map(Object.entries(planLimits[planId])))
  ));
  return limits;
}

它抛出另一个错误Unexpected parentheses around single function argument having a body with no curly braces arrow-parens

我的问题:

1) 我想我可以通过在 curry 括号内插入 return null 来修复我的第一个版本。但是有没有更好、更优雅的方式呢?虚假的 return 声明在这种情况下没有意义

2) 为什么第二个版本失败了?不是等同于第一个版本吗?

如果我使用 forEach 而不是 map,它不会导致 array-callback-return lint 错误

 Object.keys(planLimits).forEach((planId) => (
    const limitMap = new Map(Object.entries(planLimits[planId]));
    limits.set(planId, limitMap);
  ));

TLDR:ESLint 和函数 Return 值

此问题是由于在使用 map() 时未 return 值引起的,根据文档查看 results 的预期...

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. (Source: MDN WebDocs.)

JavaScript

中的问题演示

有了这个JS代码示例,里面展示了一组元素...

  var newarray = [];
  array.map( (item, index) => {
      newarray.push('<li>' + item + '</li>');
  });

我收到这个错误...

  Expected to return a value in arrow function  array-callback-return

如果我在上面的函数中添加一个 return,错误就会消失,就像这样:

  var newarray = array.map( (item, index) => {
      return '<li>' + item + '</li>';
  });

`map()` - 那么我为什么要使用它?

你也可以在其他地方清楚地看到,在 MDN 文档上,returned 是,"一个新数组,每个元素都是 [[=43= 的结果] 回调函数的值。" 因此,如果您正在使用 map(),那么也使用 return returnvalue!

也是一个很好的主意

map() 是一个强大的工具。不要把那个工具扔掉。

嗯,公认的答案提倡使用 'forEach,',这是正确的。请阅读以下来自ESLint documentation

的解释

Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.