[英]How can I clean up this if-else function? (Javascript ES6)
我是初学者 React 开发人员。
我正在清理我的代码。
我试图尽可能地摆脱 if-else 语句,但我不知道如何处理这个函数。
const calc = () => {
if (100 < responsiveWidth.phone) {
setPerPage(1);
} else if (100 < responsiveWidth.tablet) {
setPerPage(2);
} else if (100 < responsiveWidth.smallDesktop) {
setPerPage(3);
} else if (100 < responsiveWidth.desktop) {
setPerPage(4);
} else {
setPerPage(6);
}
};
我真的很讨厌这段代码。 你能帮我吗?
您可以找到索引 ( Array#findIndex
) 并添加一个。
const
widths = [width.phone, width.tablet, width.smallDesktop, width.desktop],
calc = width => setPerPage(widths.findIndex(w => width < w) + 1) || 6);
您可以使用 Switch-case 语句代替 if-else ,并使用对象解构代替重复 'width.sth'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.