首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ES6 javascript常量-返回错误

ES6 javascript常量-返回错误
EN

Stack Overflow用户
提问于 2017-01-20 02:46:53
回答 3查看 92关注 0票数 0

在测试模块上运行lint表示出现错误:

代码语言:javascript
复制
module.exports = (x) => {
  if (x % 2 === 0) {
    return 'even';
  } else if (x % 2 === 1) {
    return 'odd';
  } else if (x > 100) {
    return 'big';
  } else if (x < 0) {
    return 'negative';
  }
};

运行ESLint:

代码语言:javascript
复制
> yarn lint
../server/modules/my-awesome-module.js (1/0)
✖  3:22  Expected to return a value at the end of this function  consistent-return
✖ 1 error (7:35:56 PM)
error Command failed with exit code 1.

在这种情况下,正确的ES6编码是什么?感谢您的反馈

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-01-20 02:48:43

你没有else的案子。如果您的ifelse if条件都不满足,则没有返回值。

您可以很容易地添加一个默认的else块,或者只是在函数的末尾添加一个简单的返回。

票数 2
EN

Stack Overflow用户

发布于 2017-01-20 02:51:40

问题在于,基于某些代码路径(任何if/else子句),函数可能会返回值。但是,在没有一个案例匹配的情况下(例如,x=50.5),不会返回任何内容。出于一致性的目的,函数应该返回一些内容。

一个示例解决方案是:

代码语言:javascript
复制
module.exports = (x) => {
  if (x % 2 === 0) {
    return 'even';
  } else if (x % 2 === 1) {
    return 'odd';
  } else if (x > 100) {
    return 'big';
  } else if (x < 0) {
    return 'negative';
  }

  return 'none'
};
票数 0
EN

Stack Overflow用户

发布于 2017-01-20 02:51:48

您可以考虑将代码片段更改为

代码语言:javascript
复制
module.exports = (x) => {
  var result = "";
  if (x % 2 === 0) {
    result = "even";
  } else if (x % 2 === 1) {
    result = "odd";
  } else if (x > 100) {
    result = "big";
  } else if (x < 0) {
    result = "negative";
  }
  return result;
};

希望能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41749432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档