0

Is there a better way to do check the condition of AddressIndex?

if (AddressIndex == 104 || AddressIndex == 107 || AddressIndex == 108 || AddressIndex == 133 || AddressIndex == 155 || AddressIndex == 165 || AddressIndex ==  167 || AddressIndex == 168 || AddressIndex == 182 || AddressIndex == 214 || AddressIndex == 246 || AddressIndex == 260 || AddressIndex == 341 || AddressIndex == 345)

{

alert ("Sorry - We don't deliver to this address.");

}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Matthew
  • 55
  • 2
  • 9

4 Answers4

2

As @dsimer says, I think that's the best way to go. It'd look something like:

switch AddressIndex {
  case 104:
  case 107:
  case 108:
  case ...:
  case ...:
    alert("Sorry - We don't deliver to this address.");
  break;
}

I need not enter all the numbers for you.

ddavison
  • 28,221
  • 15
  • 85
  • 110
0

You could always use a switch statement.

dsimer
  • 115
  • 6
  • Any reason for the downrate? I gave a valid answer - am I expected to write out an explanation and code code when I offer a direct reference link to a source that will present it better than I ever could? – dsimer Feb 06 '14 at 21:52
0

If you use jQuery:

var a = new Array(104, 107, 108, 133, 155,
                  165, 167, 168, 182, 214,
                  246, 260, 341, 345);
if($.inArray(AddressIndex, a))
{
    alert ("Sorry - We don't deliver to this address.");
}

Otherwise you can use the indexOf method:

var a = new Array(104, 107, 108, 133, 155,
                  165, 167, 168, 182, 214,
                  246, 260, 341, 345);

if(a.indexOf(AddressIndex) != -1)
{
    alert ("Sorry - We don't deliver to this address.");
}

And there's always a switch as a last resort:

switch(AddressIndex)
{
    case 104:
    case 107:
    case 108:
    case 133:
    case 155:
    case 165:
    case 167:
    case 168:
    case 182:
    case 214:
    case 246:
    case 260:
    case 341:
    case 345:
        alert ("Sorry - We don't deliver to this address.");
    break;
}
Entity
  • 7,972
  • 21
  • 79
  • 122
0

In terms of performance a hash lookup would be fastest:

var nondelivery = {
  104: true, 107: true, 108: true, 133: true, 155: true,
  165: true, 167: true, 168: true, 182: true, 214: true,
  246: true, 260: true, 341: true, 345: true };

if( nondelivery[AddressIndex] )
  alert ("Sorry - We don't deliver to this address.");

This is of course only academic; a speed difference would only be noticed in a loop with many iterations.

Matt
  • 20,108
  • 1
  • 57
  • 70