在测试模块上运行lint表示出现错误:
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:
> 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编码是什么?感谢您的反馈
发布于 2017-01-20 02:48:43
你没有else的案子。如果您的if或else if条件都不满足,则没有返回值。
您可以很容易地添加一个默认的else块,或者只是在函数的末尾添加一个简单的返回。
发布于 2017-01-20 02:51:40
问题在于,基于某些代码路径(任何if/else子句),函数可能会返回值。但是,在没有一个案例匹配的情况下(例如,x=50.5),不会返回任何内容。出于一致性的目的,函数应该返回一些内容。
一个示例解决方案是:
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'
};发布于 2017-01-20 02:51:48
您可以考虑将代码片段更改为
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;
};
希望能有所帮助
https://stackoverflow.com/questions/41749432
复制相似问题