简体   繁体   中英

Eloquent JavaScript Chapter 5 Exercise

    function average(array) {
  function plus(a, b) { return a + b; }
  return array.reduce(plus) / array.length;
}

var byName = {};
ancestry.forEach(function(person) {
  byName[person.name] = person;
});

var differences = ancestry.filter(function(person) {
  return byName[person.mother] != null;
}).map(function(person) {
  return person.born - byName[person.mother].born;
});

console.log(average(differences));
// 31.2

This code is from an exercise within chapter 5 from the book "Eloquent JavaScript". The data within the ancestry is not included here. I have two questions.

My first question is about the variable byName and how it is used within the forEach method. My opinion of what is happening is the forEach method is iterating through the ancestry object to find an element and then input said element in the byName object somehow.

I have another question concerning the variable differences . My opinion of what is happening is the filter method iterate the ancestry object selecting only elements that has a mother then this will be mapped into another array somehow.

From what i understand, the forEach method loops through the array, and put all values from the array to the byName collection by key (name) and value (person object) pairs which you can reference to a person object by his/her name. The map method will make a new array that store the difference between each person's age and his/her mother's from the array that was filtered (persons that didn't have mother have been removed). The variable differences will store those values Sorry for my English.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM