【问题标题】:set a boolean variable to true and another ones to false in javascript?在javascript中将一个布尔变量设置为true,将另一个变量设置为false?
【发布时间】:2021-04-17 22:35:13
【问题描述】:

我想知道是否有办法可以简化这段代码:

        switch(visibleMenu) {
            case "menu": {
                mainMenu = true;
                assignment = false;
                temary = false;
                break;
            }
            case "asignment": {
                mainMenu = false;
                assignment = true;
                temary = false;
                break;
            }
            case "temary": {
                mainMenu = false;
                assignment = false;
                temary = true;
            }
        }

我不喜欢每个单词重复这么多次。想法?

【问题讨论】:

  • 为什么需要设置额外的变量?例如,为什么不只检查 visibleMenu === “assignment”?你可以更进一步,定义一个枚举,这样你就有了 visibleMenu === Menu.Assignment 而不是直接的字符串比较

标签: javascript algorithm switch-statement boolean


【解决方案1】:

看来这样就可以了:

 mainMenu = visibleMenu === 'menu';
 assignment = visibleMenu === 'asignment';
 temary = visibleMenu === 'temary';

不需要switch声明

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 2010-10-13
    • 2018-11-23
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多