Shorten JS if or statement

This question already has an answer here:

  • How do I check if an array includes an object in JavaScript? 40 answers

  • You can use use Array.indexOf

    [1,2,3,4].indexOf(x) !== -1
    

    You can also use objects as some kind of hash map:

    //Note: Keys will be coerced to strings so
    // don't use this method if you are looking for an object or if you need
    // to distinguish the number 1 from the string "1"
    my_values = {1:true, 2:true, 3:true, 'foo':true}
    my_values.hasOwnProperty('foo')
    

    By the way, in most cases you should usi the "===" strict equality operator instead of the == operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.


    If your cases are not that simple to be expressed by this:

    if (1 <= x && x <= 4)
    

    You could use an array and indexOf :

    if ([1,2,3,4].indexOf(x) > -1)
    

    Note that indexOf might need to be re-implemented.


    Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.

    Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.

    链接地址: http://www.djcxy.com/p/75062.html

    上一篇: 将字符串true / false转换为布尔值

    下一篇: 缩短JS if或语句