ES6 javascript 常量-return 错误
ES6 javascript constant-return error
运行 测试模块上的 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 编码是什么?
感谢反馈
您没有 else
案例。如果满足 if
或 else if
条件中的 none,则没有 return 值。
您可以轻松地在函数末尾添加默认 else
块或简单的 return。
问题是基于某些代码路径(任何 if/else 子句),函数可能会返回一个值。但是,在 none 个案例匹配的情况下(例如,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'
};
您可以考虑将代码片段更改为
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;
};
希望对您有所帮助
运行 测试模块上的 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 编码是什么? 感谢反馈
您没有 else
案例。如果满足 if
或 else if
条件中的 none,则没有 return 值。
您可以轻松地在函数末尾添加默认 else
块或简单的 return。
问题是基于某些代码路径(任何 if/else 子句),函数可能会返回一个值。但是,在 none 个案例匹配的情况下(例如,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'
};
您可以考虑将代码片段更改为
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;
};
希望对您有所帮助