IN Statement in Javascript functions, as in SQL

I tried the following, but it threw 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 SQL in SQL

+4
source share
6 answers

You can use the function below for the same purpose, the second parameter can be an array or an object, and the first parameter is the value you are looking for in an 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 passes through inherited properties as well

ie in some where are your included js libraries

 Array.prototype.foo = 10; 

than

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

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

EDITED ::

Thanks to everyone for the comments ... this is an updated code, I thought it was better to keep the old function too. therefore, some may notice the difference.

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

You can use indexOf

 ['X', 'Y', 'Z', '0'].indexOf('Z') > 2 ['X', 'Y', 'Z', '0'].indexOf('T') > -1 if (['X', 'Y', 'Z', '0'].indexOf($get('sslot_hf0').value) !== -1) { //... } 
+3
source

in does not work similarly in Javascript. You will have to use several comparisons to separate them using the || (or OR ).

+1
source

If you need useful dialing features and don't mind adding a library, check underscorejs

Otherwise, expect entries for loops for cyclic values ​​and performing equality checks.

0
source

Create array

and use jquery.inArray () to check

read here for more http://api.jquery.com/jQuery.inArray/

0
source

you can do this, beautifully and simply, store the values ​​in an array and use IN

  var temparr = ['x', 'y', 'z', '0']; if (!$get('sslot_hf0').value in temparr) { $get('sslot_hf0').value = 'X'; } 

hope this helps

-1
source

All Articles