【问题标题】:How can I clean up this if-else function? (Javascript ES6)如何清理这个 if-else 函数? (Javascript ES6)
【发布时间】:2025-11-25 10:45:02
【问题描述】:

我是 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);
        }
    };

我真的很讨厌这段代码。 你能帮帮我吗?

【问题讨论】:

  • 有效吗? width 呢?它是否同时是一个数字一个对象?
  • 你“讨厌”这段代码的什么地方?它非常简单、清晰、易于理解。
  • 您为什么需要所有这些Number() 电话?
  • 我修改了问题。这是一个错字。对不起。
  • 我不喜欢的是可读性差,不想写重复的代码。

标签: javascript reactjs if-statement refactoring code-cleanup


【解决方案1】:

您可以找到索引 (Array#findIndex) 并添加一个。

const 
    widths = [width.phone, width.tablet, width.smallDesktop, width.desktop],
    calc = width => setPerPage(widths.findIndex(w => width < w) + 1) || 6);

【讨论】:

  • 我可能会使用[width.phone, width.table, width.smallDesktop, width.desktop, width.desktop, Infinity] 而不是|| 6。甚至可能以0(或-Infinitiy)开始数组并删除+1
  • 我修改了问题。这是一个错字。对不起。可以再看一遍题的代码吗?
  • 你帮了大忙。我将学习更多关于 ES6 的知识。非常感谢。