简体   繁体   English

使用简单箭头 function 修复“一致返回”linter 问题

[英]Fixing 'consistent-return' linter issue with simple arrow function

As title, I have an arrow function with the error.作为标题,我有一个带有错误的箭头 function。 How can I refactor it so the error goes away?如何重构它以使错误消失?

Expected to return a value at the end of arrow function consistent-return预计在箭头 function 的末尾返回一个值一致返回

This is my code:这是我的代码:

// Disable default form submission when user hits enter.
const $facetInput = $('.facet-input');
const $submitButton = $('.facet-submit');

$facetInput.on('keydown', (event) => {
  if ((event.key === 'enter' || event.keyCode === 13) && event.target !== $submitButton) {
    event.preventDefault();
    return false;
  }
});

Thanks!谢谢!

By always explicitly returning a value under all code branches :通过始终在所有代码分支下显式返回一个值

$facetInput.on('keydown', (event) => {
  if ((event.key === 'enter' || event.keyCode === 13) && event.target !== $submitButton) {
    event.preventDefault();
    return false;
  }
  return <something else>; // false, true, 'whatever' - up to you
});

Assuming this is eslint (but really regardless of the linter), there is an implicit return undefined if your if (condition) does not evaluate to true.假设这是 eslint(但实际上与 linter 无关),如果您的if (condition)未计算为 true,则会有一个隐式return undefined

One of the confusing aspects of JavaScript is that any function may or may not return a value at any point in time. JavaScript 令人困惑的方面之一是任何 function 可能会或可能不会在任何时间点返回值。 When a function exits without any return statement executing, the function returns undefined.当 function 退出且未执行任何 return 语句时,function 返回 undefined。 Similarly, calling return without specifying any value will cause the function to return undefined.同样,在没有指定任何值的情况下调用 return 将导致 function 返回 undefined。 Only when return is called with a value is there a change in the function's return value.只有当使用一个值调用 return 时,函数的返回值才会发生变化。

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

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