Reduce multiple ORs in IF statement in JavaScript

前端 未结 8 473
借酒劲吻你
借酒劲吻你 2020-12-07 02:17

Is there a simpler way to rewrite the following condition in JavaScript?

if ((x == 1) || (x == 3) || (x == 4) || (x == 17) || (x == 80)) {...}
相关标签:
8条回答
  • 2020-12-07 02:56
    switch (x) {
        case 1:
        case 3:
        case 4:
        case 17:
        case 80:
            //code
            break;
        default:
            //code
    }
    
    0 讨论(0)
  • 2020-12-07 02:59

    Inspired by @Santosh I created a simplified version:

    const input = x => [1, 3, 4, 17, 80].includes(x);
    
    console.log(input(10));
    console.log(input(1));

    0 讨论(0)
提交回复
热议问题