JS advanced — function as return value to use, expand, sort

Time:2020-10-14

Function is used as return value to expand and sort

 

Sorting, each file has a name, size, time, can be sorted according to the value of an attribute

Function as the return value

Function as parameter

 

//Sorting, each file has a name, size, time, can be sorted according to the value of an attribute

    //Three movies. They have names, sizes and release times
    function File(name, size, time) {
      this.name  =Name; // movie name
      this.size  =Size; // movie size
      this.time  =Time; // the release time of the movie
    }
    var f1 = new File("jack.avi", "400M", "1997-12-12");
    var f2 = new File("tom.avi", "200M", "2017-12-12");
    var f3 = new File("xiaosu.avi", "800M", "2010-12-12");
    var arr = [f1, f2, f3];


    function fn(attr) {
      //Function as the return value
      return function getSort(obj1, obj2) {
        if (obj1 > obj2) {
          return 1;
        } else if (obj1 == obj2) {
          return 0;
        } else {
          return -1;
        }
      }
    }

//Function as parameter
    var ff = fn("size");
    for (var i = 0; i < arr.length; i++) {
      console.log(arr[i].name + "===========>" + arr[i].size + "======>" + arr[i].time);
    }