0

I have a sample code:

var find = ['iphone 3', 'iphone 4', 'iphone 5'];
var search = 'iphone 5';
for(i=0; i<find.length; i++) {
   if(search == find[i]) {
      alert('Yes');
   } else {
      alert('No');
   }
}

When I run code, result 2 alert(alert('Yes') and alert('No')), but result exactly is only a alert('Yes'), how to fix it ?

4
  • This seems to be working completely fine. Two Nos followed by one Yes. Commented Dec 10, 2012 at 1:52
  • @YogendraSingh: I think the OP doesn't want the "no"'s to show Commented Dec 10, 2012 at 1:55
  • @EliasVanOotegem: I answered that part with an if. Commented Dec 10, 2012 at 1:58
  • @YogendraSingh: So I see, it's pretty much exactly the same as I answered. Also: no need for the present var in your anser, just if (i < find.length) will work: you're using a break statement, if that break is never encountered, i === find.length, else, it'll always be smaller. nitpicking, I know, but I like to use as little vars as possible Commented Dec 10, 2012 at 2:03

3 Answers 3

1

If I understand your question correctly, you don't want no to be alerted when there is no match found:

var find = ['iphone 3', 'iphone 4', 'iphone 5'];
var search = 'iphone 5';
for(i=0; i<find.length; i++)
{
    if(search == find[i])
    {
       alert('Yes');
       break;//stop loop, found match
    }
}

Just don't provide the else branch. Oh, and if you don't care about older browsers:

if (find.indexOf(search) !== -1)
{
    alert('yes');
}
Sign up to request clarification or add additional context in comments.

Comments

1

This can be done simply with .indexOf:

if ( find.indexOf( search ) > -1 ) {

    alert('Yes');

} else {

    alert('No');

}

Replace this with the entirety of your code excluding the variable declarations.

Comments

0

If you want to alert the match found then use a flag to mark where match was found or no. In the end, use the flag to alert the respective message as below:

 var find = ['iphone 3', 'iphone 4', 'iphone 5'];
 var search = 'iphone 5';
 var present = false;
 for(i=0; i<find.length; i++) {
     if(search == find[i]) {
       present = true;
       break;
     }
 }
 if(present) {
  alert('Yes');
 } else {
  alert('No');
 }

Please Note: There could be better ways but trying the help following your algorithm only.

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.