0

a little twist on the usual "finding string in an array" question:

I currently know how to find a string in an array, using a for loop and if statement. But what I want to do is return an option if no matching string can be found once iterating through the entire array. The obvious problem is that if I include an else option in my current if-statement, each iteration that there is no match moves to the else.

So basically, I want to scan through the entire array.. IF there's a match I want to print "abc" and if there is no match at all I want to print "xyz". How do I do this? Thanks (super novice here :)).

var guestList = [
"MANDY",
"JEMMA",
"DAVE",
"BOB",
"SARAH",
"MIKE",
"SUZY"
];

var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase();

for (var i=0; i<guestList.length; i++){
    if (guestName === guestList[i]){
        alert("Hi " + guestName + " You are on the list! Enjoy The Club");
    }
}
Dude
  • 145
  • 1
  • 9
  • see this post http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – Saif Feb 04 '15 at 06:58

3 Answers3

1

No for loops required

if(guestList.indexOf(guestName) === -1)
   return "xyz"
else
  return "abc"
shawnnyglum
  • 211
  • 4
  • 14
0

If you still want to print the guest name, you can give a default guest name, and than it might be changed or not during the for loop:

    var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase();
    var member = "GUEST";
    for (var i=0; i < guestList.length; i++) {
        if (guestName === guestList[i]){
            member = guestName;
            break;
        }
    }
    alert("Hi " + member);

Or with jQuery and without a for loop:

var member = "GUEST";
if ($.inArray(guestName, guestList) > -1) {
    member = guestName;
}
alert("Hi " + member);

See the documentation of jquery inArray:

http://api.jquery.com/jquery.inarray/

Guy
  • 1,547
  • 1
  • 18
  • 29
0

Try this code:

var guestList = [
  "MANDY",
  "JEMMA",
  "DAVE",
  "BOB",
  "SARAH",
  "MIKE",
  "SUZY"
];

var guestName = prompt("Hello, welcome to The Club. What is your name?").toUpperCase();

var greet = "xyz";//put the default text here
for (var i = 0; i < guestList.length; i++) {
  if (guestName === guestList[i]) {
    greet = "Hi " + guestName + " You are on the list! Enjoy The Club";
    break;//match found, stop loop
  }
}
alert(greet);//greetings here