Reduce multiple ORs in IF statement in JavaScript

前端 未结 8 573
借酒劲吻你
借酒劲吻你 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:40

    many options

    if ([0, 1, 3, 4, 17, 80].indexOf(x) > 0)
    
    if(/^(1|3|4|17|80)$/.test(x))
    
    if($.inArray(x, [1, 3, 4, 17, 80]) 
    

    another one, based on Ed's answer

    function list() {
        for (var i = 0, o = {}; i < arguments.length; i++)
            o[arguments[i]] = '';
        return o;
    }
    
    
    if(x in list(1, 3, 4, 17, 80))...
    

提交回复
热议问题