Jquery: several comparations inside an if, any way to write it shorter?
have this line:
if($('#address_nations_id').val() != 105 && $('#address_nations_id').val() != 74)
Is there any way to make it shorter?
I tried this:
if($('#address_nations_id').val() !=开发者_运维知识库 105 && != 74)
But it doesnt work.
Any idea?
Regards
Javier
Since I'm guessing (based on the ID) you want to check many more, you can use $.inArray()
to expand that list easily, for example:
if($.inArray($('#address_nations_id').val(), ["105", "74"]) > -1)
You can give it a try here, keep in mind you'll need strings for this method, since JavaScript's weak typing with a ==
doesn't work here, and .val()
returns a string.
One thing you can do is to get the value beforehand:
var val = $('#address_nations_id').val();
if(val != 105 && val != 74)
Which is better anyway as you do only one method call instead of two.
If you have a lot of values, I would create a lookup table like so:
var values = {
"105": 1,
"74": 1
}
and do
if(!($('#address_nations_id').val() in values)) {
//...
}
This should be faster than searching a value in an array. (not sure about this).
var val = $('#address_nations_id').val();
if(val != '105' && val != '74') {
//do stuff
}
Edit :
$('#address_nations_id').val()
returns a string not a number
I'd go with Felix's suggestion. But just for completeness:
On browsers that have the indexOf
on arrays, you could do:
if ([105, 74].indexOf(parseInt($('#address_nations_id').val())) >= 0)
...but I wouldn't recommend it for just two values. It's less clear, unnecessarily complex, and not all browsers have it (yet). Most of those criticisms apply to using jQuery's inArray
function as well.
There's also switch
:
switch (parseInt($('#address_nations_id').val())) {
case 105:
case 74:
break;
default:
/* do your thing here *?
break;
}
...but that hardly qualifies as shorter, almost certainly wouldn't be appropriate for just two values.
精彩评论