javascript 警告 ESLint 规则下的意外未命名函数 func-names

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52735032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:01:26  来源:igfitidea点击:

Warning Unexpected unnamed function func-names under, ESLint rule

javascripteslintrules

提问by Zapar Siddik

My eslintversion is 4.18.2, it would give a warning like this:

我的eslint版本是 4.18.2,它会给出这样的警告:

Unexpected unnamed function
Expected an assignment or function call and instead saw an expression

意外的未命名函数
预期是赋值或函数调用,而是看到了一个表达式

When defining functions in such a way:

当以这种方式定义函数时:

 const farmerIds = a.reduce((function (hash) {
  return function (prev, curr) {
    !hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
    return prev;
  };
}(Object.create(null))), []);

回答by Patrick Hund

These are two different issues…

这是两个不同的问题……

Unexpected unnamed function

意外的未命名函数

This is, as pointed out by Constantin, the ESLint rule func-names.

正如康斯坦丁所指出的,这就是 ESLint 规则func-names

If you don't want to disable this rule, you can either use names for your functions, like so:

如果您不想禁用此规则,您可以为您的函数使用名称,如下所示:

const farmerIds = a.reduce((function reducer(hash) {
  return function fn(prev, curr) {
    !hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
    return prev;
  };
}(Object.create(null))), []);

Or, and this I would recommend personally, use arrow functions:

或者,我个人建议使用箭头函数:

const farmerIds = a.reduce(
  (hash => {
    return (prev, curr) => {
      !hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));
      return prev;
    };
  })(Object.create(null)),
  []
);

Expected an assignment or function call and instead saw an expression

期望赋值或函数调用,而是看到了一个表达式

ESLint is complaining about this line, which is indeed an expression, not an assignment or function call:

ESLint 抱怨这一行,它确实是一个表达式,而不是赋值或函数调用:

!hash[curr.farmerId] && (hash[curr.farmerId] = prev.push(curr));

You can rewrite it as an ifstatement:

您可以将其重写为if语句:

if (!hash[curr.farmerId]) {
  hash[curr.farmerId] = prev.push(curr);
}

Fixing both

修复两者

Putting the code examples above together, this code should run without ESLint complaining:

将上面的代码示例放在一起,这段代码应该可以在没有 ESLint 抱怨的情况下运行:

const farmerIds = a.reduce(
  (hash => (prev, curr) => {
    if (!hash[curr.farmerId]) {
      hash[curr.farmerId] = prev.push(curr);
    }
    return prev;
  })(Object.create(null)),
  []
);

Note that I've also removed the curly braces around the body of the first arrow function, which is a nice additional feature of arrows to keep the code more concise.

请注意,我还删除了第一个箭头函数主体周围的花括号,这是箭头的一个很好的附加功能,可以使代码更加简洁。