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");
    }
}
1

3 Answers 3

1

No for loops required

if(guestList.indexOf(guestName) === -1)
   return "xyz"
else
  return "abc"

Sign up to request clarification or add additional context in comments.

1 Comment

return guestList.indexOf(guestName) === -1 ? "xyz" : "abc";
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/

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.