PDA

View Full Version : Help with a simple array search


Jen333
06-26-2008, 02:09 PM
Hi! I am new to javascript and am having trouble with searching for matching items in an array. What I am trying to achieve is this:
Array : with makes of user's cars
Ask users to input what make of car they have
Search the array to see if one of these matches
If yes, say congratulations you are in our database
If not, say sorry there is no record of your car entry

This is my code:

var carArray = ['peugeot' , 'ferrari' , 'fiat' , 'mazda' , 'mercedes'];

var carMake = window.prompt('Please enter your car make');

for (var count = 0; count < carArray.length; count = count + 1)
{
if (carArray[count] == carMake)
{
document.write ('Thank you, your car is in our database');
}
else
{
document.write ('sorry we were unable to locate your car make');
}
}

The problem I am finding is that as it searches each item, I get 5 messages written out on the screen, if I input 'Mercedes' I get 1 match message and then 4 messages telling me sorry we were unable to locate the car make! How can I redesign this so that it looks through the whole database, but just applies the IF and ELSE statements when there is just one match or no matches?

Thanks for your help!

Kor
06-26-2008, 02:31 PM
You should write the answer outside the loop:

var carArray = ['peugeot' , 'ferrari' , 'fiat' , 'mazda' , 'mercedes'];
var carMake = window.prompt('Please enter your car make');
var message='sorry we were unable to locate your car make';
for (var count=0; count<carArray.length;count++){
if(carArray[count]==carMake){
message='Thank you, your car is in our database';
break
}
}
document.write(message);

Jen333
06-26-2008, 02:57 PM
Thank you!
Just one thing tho, I see that this works when there is no match and it skips the loop and just prints out that there is no match, but when there is a match it seems to write out both the message saying there is a match and then also write out the no match message that comes after the loop.. is there a way to make it only do one or the other?
Thanks again!

Kor
06-26-2008, 03:24 PM
Thank you!
but when there is a match it seems to write out both the message saying there is a match and then also write out the no match message that comes after the loop.. is there a way to make it only do one or the other?
Thanks again!
I don't get it. The code will display a single message. If the prompt matches one of the array's elements, the 'Thank you...' message is written. If not, the 'sorry we ...' message is written.

How did you get 2 messages on the same time? Can I see the whole document of yours?

Jen333
06-26-2008, 04:38 PM
Sorry! I was still uploading an old version of my file! Your code works perfectly!! thanks so much for your help :thumbsup: