使用forEach循环迭代数组

时间:2017-05-31 11:16:36

标签: javascript

在此项目中有3个文件,index.htmlhelper.jsresumeBuilder.js。最后一个是我一直在工作的文件。     我在这个项目中遇到的问题是,我无法确定如何制作images array,它位于要在我的简历中显示的项目数组中,并且同样适用于学校内的onLineCourses array阵列。这个在线学校需要制作所有阵列 forEach循环。如果有人可以帮忙写下我必须写的代码来显示它,我正在搜索一周而且无法弄明白!

resumeBuilder.js

var projects = {
  "projects" : [
    {
      "title":"",
      "location":"",
      "dates":"",
      "description":"",
    },
    {
      "title":"",
      "location":"",
      "dates":"",
      "description":"",
> 
>  "images":["", ""]

    }
  ],
};

//projects function
projects.display = function(){
  $.each(projects.projects, function(i){
    $("#projects").append(HTMLprojectStart);

    var myProjects = projects.projects[i];
    var formattedTitle =  HTMLprojectTitle.replace("%data%", myProjects.title);
    $(".project-entry:last").append(formattedTitle);
    var formattedDates =  HTMLprojectDates.replace("%data%", myProjects.dates);
      $(".project-entry:last").append(formattedDates);
    var  formattedDescription = HTMLprojectDescription.replace("%data%", myProjects.description);
      $(".project-entry:last").append(formattedDescription);

> //image array here!
>      var formattedImage = HTMLprojectImage.replace("%data%",projects.images);
>        $("#projects").append(HTMLprojectStart);
>      $(".project-entry:last").append(formattedImage);

  });
};
projects.display();

> var education = {
  "schools": [
    {
      "name" : "",
      "location" : "",
      "degree":",
      "majors":["","",""],
      "dates" : "2",
      "url" : ""
    },
    {
      "name" : "",
      "location" :"",
      "degree":"",
      "majors":[""],
      "dates" : "",
      "url" : ""
    }
  ],
  //create onLine Courses
>   "onlineCourses" : [
>     {
>       "title" : "",
>       "school" : "",
>       "dates" : "",
>       "url" : ""
>     }   ] };

//education function
education.display = function(){

  $.each(education.schools, function(i) {

  var mySchools = education.schools[i];

   $("#education").append(HTMLschoolStart);

  var formattedName = HTMLschoolName.replace("%data%",mySchools.name);
  var formattedDegree = HTMLschoolDegree.replace("%data%",mySchools.degree);
  var formattedNameDegree = formattedName + formattedDegree;
  $(".education-entry:last").append(formattedNameDegree);
  var  formattedDates = HTMLschoolDates.replace("%data%",mySchools.dates);
  $(".education-entry:last").append(formattedDates);
    var  formattedLocation = HTMLschoolLocation.replace("%data%",mySchools.location);
  $(".education-entry:last").append(formattedLocation);
    var  formattedMajor = HTMLschoolMajor.replace("%data%",mySchools.majors);
  $(".education-entry:last").append(formattedMajor);

});
//onLine courses here

>  $("#education").append(HTMLonlineClasses);  
> $("#education").append(HTMLschoolStart);   var courses =
> education.onlineCourses;   var formattedTitle =
> HTMLonlineTitle.replace("%data%", courses.title);    var
> formattedSchool = HTMLonlineSchool.replace("%data%",courses.name);   
> var formattedDates = HTMLonlineDates.replace("%data%", courses.dates);
> var formattedOnline = formattedTitle + formattedSchool +
> formattedDates;
>      $(".education-entry:last").append(formattedOnline);
> 
> };
> 
> education.display();


helper.js

> /*

This file contains all of the code running in the background that makes resumeBuilder.js possible. We call these helper functions because they support your code in this course.

Don't worry, you'll learn what's going on in this file throughout the course. You won't need to make any changes to it until you start experimenting with inserting a Google Map in Problem Set 3.

/*
These are HTML strings. As part of the course, you'll be using JavaScript functions
replace the %data% placeholder text you see in them.
*/
var HTMLheaderName = '<h1 id="name">%data%</h1>';
var HTMLheaderRole = '<span>%data%</span><hr>';

var HTMLcontactGeneric = '<li class="flex-item"><span class="orange-text">%contact%</span><span class="white-text">%data%</span></li>';
var HTMLmobile = '<li class="flex-item"><span class="orange-text">mobile</span><span class="white-text">%data%</span></li>';
var HTMLemail = '<li class="flex-item"><span class="orange-text">email</span><span class="white-text">%data%</span></li>';
var HTMLtwitter = '<li class="flex-item"><span class="orange-text">twitter</span><span class="white-text">%data%</span></li>';
var HTMLgithub = '<li class="flex-item"><span class="orange-text">github</span><span class="white-text">%data%</span></li>';
var HTMLblog = '<li class="flex-item"><span class="orange-text">blog</span><span class="white-text">%data%</span></li>';
var HTMLlocation = '<li class="flex-item"><span class="orange-text">location</span><span class="white-text">%data%</span></li>';

var HTMLbioPic = '<img src="%data%" class="biopic">';
var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>';

var HTMLskillsStart = '<h3 id="skills-h3">Skills at a Glance:</h3><ul id="skills" class="flex-column"></ul>';
var HTMLskills = '<li class="flex-item"><span class="white-text">%data%</span></li>';

var HTMLworkStart = '<div class="work-entry"></div>';
var HTMLworkEmployer = '<a href="#">%data%';
var HTMLworkTitle = ' - %data%</a>';
var HTMLworkDates = '<div class="date-text">%data%</div>';
var HTMLworkLocation = '<div class="location-text">%data%</div>';
var HTMLworkDescription = '<p><br>%data%</p>';

var HTMLprojectStart = '<div class="project-entry"></div>';
var HTMLprojectTitle = '<a href="#">%data%</a>';
var HTMLprojectDates = '<div class="date-text">%data%</div>';
var HTMLprojectDescription = '<p><br>%data%</p>';
var HTMLprojectImage = '<img src="%data%">';

var HTMLschoolStart = '<div class="education-entry"></div>';
var HTMLschoolName = '<a href="#">%data%';
var HTMLschoolDegree = ' -- %data%</a>';
var HTMLschoolDates = '<div class="date-text">%data%</div>';
var HTMLschoolLocation = '<div class="location-text">%data%</div>';
var HTMLschoolMajor = '<em><br>Major: %data%</em>';

var HTMLonlineClasses = '<h3>Online Classes</h3>';
var HTMLonlineTitle = '<a href="#">%data%';
var HTMLonlineSchool = ' - %data%</a>';
var HTMLonlineDates = '<div class="date-text">%data%</div>';
var HTMLonlineURL = '<br><a href="#">%data%</a>';

var internationalizeButton = '<button>Internationalize</button>';
var googleMap = '<div id="map"></div>';



$(document).ready(function() {
  $('button').click(function() {
    var $name = $('#name');
    var iName = inName($name.text()) || function(){};
    $name.html(iName);
  });
});

/*
The next few lines about clicks are for the Collecting Click Locations quiz in the lesson Flow Control from JavaScript Basics.
*/
var clickLocations = [];

function logClicks(x,y) {
  clickLocations.push(
    {
      x: x,
      y: y
    }
  );
  console.log('x location: ' + x + '; y location: ' + y);
}

$(document).click(function(loc) {
  // your code goes here!
});

var map;    // declares a global map variable

/*
Start here! initializeMap() is called when page is loaded.
*/
function initializeMap() {

  var locations;

  var mapOptions = {
    disableDefaultUI: true
  };

  /*
  For the map to be displayed, the googleMap var must be
  appended to #mapDiv in resumeBuilder.js.
  */
  map = new google.maps.Map(document.querySelector('#map'), mapOptions);


  /*
  locationFinder() returns an array of every location string from the JSONs
  written for bio, education, and work.
  */
  function locationFinder() {

    // initializes an empty array
    var locations = [];

    // adds the single location property from bio to the locations array
    locations.push(bio.contacts.location);

    // iterates through school locations and appends each location to
    // the locations array. Note that forEach is used for array iteration
    // as described in the Udacity FEND Style Guide:
    // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop
    education.schools.forEach(function(school){
      locations.push(school.location);
    });

    // iterates through work locations and appends each location to
    // the locations array. Note that forEach is used for array iteration
    // as described in the Udacity FEND Style Guide:
    // https://udacity.github.io/frontend-nanodegree-styleguide/javascript.html#for-in-loop
    work.jobs.forEach(function(job){
      locations.push(job.location);
    });

    return locations;
  }

  /*
  createMapMarker(placeData) reads Google Places search results to create map pins.
  placeData is the object returned from search results containing information
  about a single location.
  */
  function createMapMarker(placeData) {

    // The next lines save location data from the search result object to local variables
    var lat = placeData.geometry.location.lat();  // latitude from the place service
    var lon = placeData.geometry.location.lng();  // longitude from the place service
    var name = placeData.formatted_address;   // name of the place from the place service
    var bounds = window.mapBounds;            // current boundaries of the map window

    // marker is an object with additional data about the pin for a single location
    var marker = new google.maps.Marker({
      map: map,
      position: placeData.geometry.location,
      title: name
    });

    // infoWindows are the little helper windows that open when you click
    // or hover over a pin on a map. They usually contain more information
    // about a location.
    var infoWindow = new google.maps.InfoWindow({
      content: name
    });

    // hmmmm, I wonder what this is about...
    google.maps.event.addListener(marker, 'click', function() {
      // your code goes here!
      //quiz 4 lesson 6
      infowindow.open(map, marker);
    });

    // this is where the pin actually gets added to the map.
    // bounds.extend() takes in a map location object
    bounds.extend(new google.maps.LatLng(lat, lon));
    // fit the map to the new marker
    map.fitBounds(bounds);
    // center the map
    map.setCenter(bounds.getCenter());
  }

  /*
  callback(results, status) makes sure the search returned results for a location.
  If so, it creates a new map marker for that location.
  */
  function callback(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      createMapMarker(results[0]);
    }
  }

  /*
  pinPoster(locations) takes in the array of locations created by locationFinder()
  and fires off Google place searches for each location
  */
  function pinPoster(locations) {

    // creates a Google place search service object. PlacesService does the work of
    // actually searching for location data.
    var service = new google.maps.places.PlacesService(map);

    // Iterates through the array of locations, creates a search object for each location
    locations.forEach(function(place){
      // the search request object
      var request = {
        query: place
      };

      // Actually searches the Google Maps API for location data and runs the callback
      // function with the search results after each search.
      service.textSearch(request, callback);
    });
  }

  // Sets the boundaries of the map based on pin locations
  window.mapBounds = new google.maps.LatLngBounds();

  // locations is an array of location strings returned from locationFinder()
  locations = locationFinder();

  // pinPoster(locations) creates pins on the map for each location in
  // the locations array
  pinPoster(locations);

}

/*
Uncomment the code below when you're ready to implement a Google Map!
*/

// Calls the initializeMap() function when the page loads
window.addEventListener('load', initializeMap);

// Vanilla JS way to listen for resizing of the window
// and adjust map bounds
window.addEventListener('resize', function(e) {
  //Make sure the map bounds get updated on page resize
  map.fitBounds(mapBounds);
});

0 个答案:

没有答案