变量函数名称Javascript

变量函数名称Javascript

本文介绍了变量函数名称Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对数组进行排序:

  myArray.sort(comparators.some_comparator); 

我有几种比较器可供选择:

 比较器= {

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

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

etc ...
}

我想写一个函数,它根据输入数据返回某个比较器。它应该从字符串输入中找出比较器,如下所示:

 函数chooseComparator(field,order){

返回比较器。+ order +_+ field +_ comparator;






$ b

所以有可能只传递函数名字符串到 sort()方法,或者我需要以某种方式传递正确的比较器的引用?

解决方案

使用下标表示法为javascript对象编制索引( obj.prop obj [prop]
$ p $ function chooseComparator(field,order){$ b> $ c>,但后一种方式您可以动态创建属性名称):


$ b返回比较器[order +_+ field +_ comparator];


$ / code>

是的,您必须将函数对象传递给 sort()函数,只是一个名字是不够的


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

这篇关于变量函数名称Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:09