javascriptin-operator

IN Operator in Javascript functions like the one in SQL


I have tried the following but it's throwing an exception:

                if (!$get('sslot_hf0').value in ('X', 'Y', 'Z', '0')) {
                $get('sslot_hf0').value = 'X';
            }

I am looking for a function similar to the IN operator in SQL


Solution

  • You can use below function for the same purpose, second param can be array or object and first param is value you are searching in array or object.

       function inStruct(val,structure)
            {
    
              for(a in structure)
                 {
                   if(structure[a] == val)
                     {
                       return true;
                     }
                 }
               return false;
            }
    if(inStruct('Z',['A','B','Z']))
        {
           //do your stuff
        }
    

    // this function traverse through inherited properties also

    i.e in some where your included js libraries

    Array.prototype.foo = 10;
    

    than

     instruct(10,[1,2,3]) // will return true
    

    same will happen for objects also. check this fiddle http://jsfiddle.net/rQ8AH/17/

    EDITED ::

    thank you all for comments ... this is the updated code, I thought it is better to keep old function also. so, some one can notice the difference.

    function inStruct(val,structure)
        {
    
          for(a in structure)
             {
    
               if(structure[a] == val && structure.hasOwnProperty(a))
                 {
                   return true;
                 }
             }
           return false;
        }