简体   繁体   中英

Variable function name Javascript

I'm sorting array:

myArray.sort(comparators.some_comparator);

and I have several comparator to choose from:

comparators = {

   asc_firstname_comparator : function(o1, o2){
    ...
   }

   desc_firstname_comparator : function(o1, o2){
    ...
   }

   etc...
}

I want to write function which returns certain comparator depending on input data. It should figure out comparator from string inputs, something like this:

function chooseComparator(field, order){

  return "comparators."+order+"_"+field+"_comparator";

}

So is it possible to pass only function name string to sort() method or I'll need to pass reference to correct comparator somehow?

use the subscript notation for indexing the javascript object ( obj.prop is the same as obj["prop"] , but the latter way you can create property names dynamically):

function chooseComparator(field, order){ 

  return comparators[order+"_"+field+"_comparator"]; 

}

and yes, you have to pass a function object to the sort() function, just a name is not enough

Actually you can create a closure instead of writing dozens of functions. Assuming asc_firstname_comparator means "sort by x.firstname ",

function compareByProperty(field, order) {
   return function (o1, o2) {
      var retval;
      if (o1[field] > o2[field])
        retval = 1;
      else if (o1[field] < o2[field])
        retval = -1;
      else
        retval = 0;
      if (order === "desc")
        retval = -retval;
      return retval;
   }
}
...
myArray.sort(compareByProperty("firstname", "asc"));

I'd do something like this.

var comparators = {
   asc_firstname_comparator : function(o1, o2){ ... }
   desc_firstname_comparator : function(o1, o2){ ... }
};

Array.prototype.customSort(comparatorName) {
    this.sort(comparators[comparatorName]);
}

var myArray = [ ... ]; // define array
myArray.customSort("asc_firstname_comparator");

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