【问题标题】:Could I simplify the following javascript logical OR code? [duplicate]我可以简化以下 javascript 逻辑 OR 代码吗? [复制]
【发布时间】:2021-11-24 22:14:07
【问题描述】:

我的项目中有一个代码,但它有点笨拙。谁能帮我简化以下代码?

if (a == "good" || a == "beautiful || a == "pretty"|| a == "excellent" || a == "superb"|| a == "spectacular")

我可以把它做成某种数组,然后在这个 if 代码中使用那个数组吗?

【问题讨论】:

  • 我觉得很好...

标签: javascript arrays simplify


【解决方案1】:
if (["good", "beautiful", "pretty", "excellent", "superb", "spectacular"].includes(a)) {...}

【讨论】:

    【解决方案2】:

    我想您可以改用 Hash-Set 结构:在 JS 中这是 Set(或在 TypeScript 中为 Set<T>):

    const positiveWords = new Set( [ "good", "beautiful", "pretty", "excellent", "superb", "spectacular" ] );
    

    用法:

    if( positiveWords.has( a ) ) {
        
    }
    

    请注意,您需要先将a 转换为小写。如果您想要不区分大小写(或不区分重音,或其他文化/区域设置特定的比较规则)then use Intl and/or localeCompare

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多