mardi 27 septembre 2016

JavaScript Tutorial

I'm completing a JavaScript tutorial and I have what will probably be a simple question from someone knowledgeable. The tutorial asked that I make a program, which cycles through two sets of arrays. utilizing a for loop to do so, to compare if there is anything that matches in the two sets of arrays. After doing so, it asked that I write an if else statement before "console.log"ing the information.

My code is as follows:

var myPlaces = ["Lumera", "Agartha", "Atlantis"];

var friendPlaces = ["Atlantis", "Mars", "Gilese B82 super earth"];

for (var i = 0; i < myPlaces.length; i++) {
  for (var j = 0; j < friendPlaces.length; j++) {
    if (myPlaces[i] === friendPlaces[j]) {

      console.log('Match: ' + myPlaces[i]);

    } else {
      console.log('Sorry, no matches.');
    }
  }
} 

The output I get is:

Sorry, no matches.
Sorry, no matches.
Sorry, no matches.
Sorry, no matches.
Sorry, no matches.
Sorry, no matches.
Match: Atlantis
Sorry, no matches.
Sorry, no matches.

My Question: I know if I remove the "else" portion of the code, it would output ONLY the "Match: Atlantis". However, it doesn't go into anymore details about how to make it only print out the match with the "else" statement still present. So, how would I go about doing this? Is the "for loop" limited in such a way, that I can't do it without introducing more logic, such as a "while loop"? Which I haven't completely grasped the concept of by the way...

Aucun commentaire:

Enregistrer un commentaire