开发者

javascript "in" strange or normal behaviour?

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


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_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜