Reduce multiple ORs in IF statement in JavaScript

前端 未结 8 571
借酒劲吻你
借酒劲吻你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 02:50

    This is a little function I found somewhere on the web:

    function oc(a) {
        var o = {};
        for (var i = 0; i < a.length; i++) {
            o[a[i]] = '';
        }
        return o;
    }
    

    Used like this:

    if (x in oc(1, 3, 4, 17, 80)) {...}
    

    I'm using it for strings myself; haven't tried with numbers, but I guess it would work.

提交回复
热议问题