views:

47

answers:

4

I have a multiple select and I made a function to check several parameters, each prints a different value in another form:

if ( (tot_v >= 10) || (perc_a < 100) ) {
 $("#DA_IDO").val('1');
}

if ( (tot_v > 3) && (tot_v < 10) && (perc_a == 100) ) {
 $("#DA_IDO").val('2');
} 

if ( (tot_v <= 3) && (perc_a == 100) ) {
 $("#DA_IDO").val('3');
}

Then we come to the incriminating if:

if ( !( array in {'One':'', 'Two':'','Three':'','Four':'','Five':''}) ) {
 $("#DA_IDO").val('5');
}

This works, but in my mind if array = (One, Ten) the if shouldn't work as at least one of the items in the array is there, instead with an array like the if is triggered.

What am I doing wrong? Is so hard to search for "javascript in" in google .-)

Thanks

+1  A: 

Here is a source to give more info on the in operator: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator

James Black
+1  A: 

The Mozilla Developer Central page should clarify what it's for:

The in operator returns true if the specified property is in the specified object.

The left hand side should be the name of a property, e.g. "One". You can't use an array of property names.

Greg
You actually can do this, at least in IE 7, Firefox 3, and Safari 3. I just ran a little test on my local machine (Windows XP), and all three of the tested browsers displayed the correct results with the following code:var keys = {'One':'', 'Two':'','Three':'','Four':'','Five':''};document.write( ('One', 'Five') in keys ); // returns truedocument.write( ('One', 'Ten') in keys ); // returns falsedocument.write( ('One', 'Three', 'Four') in keys ); // returns true
MikeWyatt
+2  A: 

I think you're misunderstanding the "in" statement. "in", in javascript, checks to see if the specified value exists as a property (or index in an array). For example:

var x = { a: 'b', c: 'd' };
if('a' in x){
  //true
}
if('b' in x){
  //false
}

What you're trying to do is determine if any of the values in the array are contained within the object. For this, you'll have to use a loop, something like this:

var possible = {'One':'', 'Two':'','Three':'','Four':'','Five':''};
//removed "array" as a variable name, since it's a bit confusing
for(var i = 0; i < values.length; i++){
  if(values[i] in possible){
    //exists
  }
}

For details, check out the Mozilla docs: https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Operators/Special%5FOperators/in%5FOperator

jvenema
Thank you very much
0plus1
A: 

It's normal behaviour, your variable 'array' is an array (as you set it to ('One','Ten')) so it not int {'One':'', 'Two':'','Three':'','Four':'','Five':''} (but 'One' is).

The reason by if block works because you are checking NOT IN ('!').

I hope I didn't miss anything here.

NawaMan