Dashuang front-end introductory training 001

The author introduces himself: Da Shuangge, The small UP owner of station b, 1 on 1 programming Tutor

Basic exercises - functions

Scene introduction:
The array that records some student information is as follows

persons = [
    {
    
     "name": "Zhang three", "age": 24, "grade": 1 },
    {
    
     "name": "li four", "age": 22, "grade": 2 },
    {
    
     "name": "Wang five", "age": 26, "grade": 1 },
    {
    
     "name": "Zhao six", "age": 23, "grade": 1 },
    {
    
     "name": "Qian seven", "age": 25, "grade": 2 },
    {
    
     "name": "Sun eight", "age": 25, "grade": 1 },
    {
    
     "name": "Zhou nine", "age": 21, "grade": 2 },
    {
    
     "name": "Wu ten", "age": 27, "grade": 1 },
    {
    
     "name": "Zheng one", "age": 23, "grade": 1 },
]

The information format of a single student is as follows

{
    "name": 姓名,
    "age": 年龄,
    "grade": 班级
}

Now implement the following functions

1 cal_aver_age_by_grade(person_list, grade)

Calculate the average age of a class.
This function accepts an array to store student information person_list, and the specified class grade
returns The average score of the class members.

If the input class does not exist, returnundefined

Answer

1cal_aver_age_by_grade(person_list, grade)

Three solutions are provided here
The first two are recommended to be mastered, and the third can be understood.

  • BasicforCirculation method
function cal_aver_age_by_grade(person_list, grade){
    
    
    var age_sum = 0;
    var count = 0;
    for(person of person_list){
    
    
        if (person["grade"] == grade) {
    
    
            age_sum += person["age"];
            count += 1
        }
    }

    if(count == 0){
    
    
        return undefined;
    }

    return age_sum / count

}
  • usefilter, mapforeach实现
function cal_aver_age_by_grade(person_list, grade){
    
    
    var grade_persons = person_list.filter(person => person.grade == grade );
    var ages = grade_persons.map(person => person.age);

    var age_sum = 0;
    ages.forEach(age => {
    
    
        age_sum += age;
    });

    return age_sum / ages.length;
}
  • *usefilter, mapreduce实现
function cal_aver_age_by_grade(person_list, grade){
    
    
    var grade_persons = person_list.filter(person => person.grade == grade );
    var ages = grade_persons.map(person => person.age);

    var age_sum = ages.reduce((a, b) => a + b, 0);
    return age_sum / ages.length;
}

code that calls the function

result = cal_aver_age_by_grade(persons, 1)
console.log(result);

expected output

24.666666666666668

Extended introductionreduce
Reference document: Array.prototype.reduce()

The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.< /span> (The anonymous function written in the brackets, that is, the reducer callback function provided by the user, accepts two parameters. The first parameter is the return value calculated by calling the function on the previous element, and the second parameter The parameter is the current element)
reduce() method, executes the "reducer" callback function provided by the user (that is, the anonymous function written in parentheses) for each element of the array in sequence, and passes in the calculated return value of the previous element.

The final result of running the reducer across all elements of the array is a single value.
The final result of running the reducer across all elements of the array is a single value.
The first time that the callback is run there is no “return value of the previous calculation”.
(Then the problem comes), execute on the first element When the callback function is called, there is no "last calculation result (previous element)".
(So you need to set the initial value, that is, set the value used by the first parameter when there is no previous element, that is, when there is no previous element to calculate the return value. The initial value is set in the return value , the second element of the return value is the initial value)

If supplied, an initial value may be used in its place.
If you need the callback function to start executing from the element with array index 0, you need to pass the initial value.
Otherwise the array element at index 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).

Otherwise, the element at array index 0 will be used as the initialValue and the iterator will start executing from the second element (index 1 instead of 0).

Helps you understand Example of reduce() - calculating the sum of all elements of an array:

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

Guess you like

Origin blog.csdn.net/python1639er/article/details/124968124