JS advanced — function as parameter

Time:2020-10-15

Functions are used as arguments

 

var arr = [1, 100, 20, 200, 40, 50, 120, 10];
    //Sort
    arr.sort();
    console.log(arr);

 

Sorting --- the function is used as a parameter, and the anonymous function is used as the parameter of the sort method. Then there are two parameters in the anonymous function at this time
var arr = [1, 100, 20, 200, 40, 50, 120, 10];
    //Sort: the function is used as a parameter, and the anonymous function is used as the parameter of the sort method. Then there are two parameters in the anonymous function,
    arr.sort(function (obj1, obj2) {
      if (obj1 > obj2) {
        return -1;
      } else if (obj1 == obj2) {
        return 0;
      } else {
        return 1;
      }
    });
    console.log(arr);

 

    var arr1 = ["acdef", "abcd", "bcedf", "bced"];
    arr1.sort(function (a, b) {
      if (a > b) {
        return 1;
      } else if (a == b) {
        return 0;
      } else {
        return -1;
      }
    });
    console.log(arr1);