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!
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!