Hai Truong IT
Hai Truong IT

Reputation: 4187

Error when compare value in array using javascript?

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 ?

Upvotes: 0

Views: 72

Answers (3)

Yogendra Singh
Yogendra Singh

Reputation: 34387

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.

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

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');
}

Upvotes: 1

David G
David G

Reputation: 96845

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.

Upvotes: 1

Related Questions