准备要排序的数组 [英] Prepare array for sorting in closure

查看:129
本文介绍了准备要排序的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的研究和谷歌搜索,Javascript似乎缺乏对语言环境感知的排序和字符串比较的支持。有 localeCompare() ,但已报告了特定于浏览器的差异,并且无法明确设置使用哪种语言环境(操作系统语言环境并不总是需要的语言环境)。在ECMAScript中有一些意图添加排序规则支持,但是在此之前,我们是靠我们自己。并且取决于结果在浏览器中的一致性如何,也许我们永远是我们自己:(。

According to my research and googling, Javascript seems to lack support for locale aware sorting and string comparisons. There is localeCompare(), but it has been reported of browser specific differencies and impossibility to explicitly set which locale is used (the OS locale is not always the one wanted). There is some intentions to add collation support inside ECMAScript, but before it, we are on our own. And depending how consistent the results are across browsers, may be we are on our own forever :(.

我有以下代码,它使数组按字母顺序排序。考虑到速度,想法来自 https://stackoverflow.com/a/11598969/1691517

I have the following code, which makes alphabetical sort of an array. It's made speed in mind, and the ideas are got from https://stackoverflow.com/a/11598969/1691517, to which I made some speed improvements.

在此示例中,单词array具有13个成员,sort-function被调用了34次。我想替换一些单词数组中的字母(您不必知道要进行哪些替换,因为这不是此问题的重点)。如果我在sort-function中进行这些替换(以开头的替换函数返回函数(a,b)),代码效率低下,因为每个数组成员进行多次替换。当然,我可以在此闭包之外进行这些替换,我的意思是在 words.sort(sortbyalphabet_timo); ,但这不是什么我想要。

In this example, the words array has 13 members and the sort-function is called 34 times. I want to replace some of the letters in the words-array (you don't have to know what replacements are made, because it's not the point in this question). If I make these replacements in sort-function ( the one that starts with return function(a, b) ), the code is inefficient, because replacements are made more than once per array member. Of course I can make these replacements outside of this closure, I mean before the line words.sort(sortbyalphabet_timo);, but it's not what I want.

问题1:是否可以在 PREPARATION STARTS和 PREPARATION ENDS行之间修改单词数组?以便排序函数使用修饰的单词数组?

Question 1: Is it possible to modify the words-array in between the lines "PREPARATION STARTS" and "PREPARATION ENDS" so that the sort function uses modified words-array?

问题2:是否可以向闭包输入参数,以便PREPARATION之间的代码STARTS和PREPARATION ENDS可以使用它们吗?我尝试过但没有成功:

Question 2: Is it possible to input arguments to the closure so that code between PREPARATION STARTS and PREPARATION ENDS can use them? I have tried this without success:

var caseinsensitive = true;
words.sort( sortbyalphabet_timo(caseinsensitive) );

最后是下面的代码示例,可以运行的示例在> http://jsfiddle.net/3E7wb/

And here is finally the code example, and the ready to run example is in http://jsfiddle.net/3E7wb/:

var sortbyalphabet_timo = (function() {
  // PREPARATION STARTS
  var i, alphabet = "-0123456789AaÀàÁáÂâÃãÄäBbCcÇçDdEeÈèÉéÊêËëFfGgHhIiÌìÍíÎîÏïJjKkLlMmNnÑñOoÒòÓóÔôÕõÖöPpQqRrSsTtUuÙùÚúÛûÜüVvWwXxYyÝýŸÿZz",
  index = {};

  i = alphabet.length;
  while (i--) index[alphabet.charCodeAt(i)] = i;
  // PREPARATION ENDS

  return function(a, b) {
    var i, len, diff;

    if (typeof a === "string" && typeof b === "string") {
      (a.length > b.length) ? len = a.length : len = b.length;
      for (i = 0; i < len; i++) {
        diff = index[a.charCodeAt(i)] - index[b.charCodeAt(i)];

        if (diff !== 0) {
          return diff;
        }
      }
      // sort the shorter first
      return a.length - b.length;
    } else {
      return 0;
    }
  };
})();

var words = ['tauschen', '66', '55', '33', 'täuschen', 'andern', 'ändern', 'Ast', 'Äste', 'dosen', 'dösen', 'Donaudam-0', 'Donaudam-1'];
$('#orig').html(words.toString());
words.sort(sortbyalphabet_timo);
$('#sorted').html(words.toString());`


推荐答案


是否可以在 PREPARATION STARTS和 PREPARATION ENDS行之间修改单词数组,以便排序功能使用修改后的单词数组?

Is it possible to modify the words-array in between the lines "PREPARATION STARTS" and "PREPARATION ENDS" so that the sort function uses modified words-array?

不,不是真的。您无权访问数组本身,您的函数只能构建比较函数,该函数稍后在数组上调用 .sort 时使用。如果需要更改数组,则需要编写一个将其作为参数的函数;例如,您可以在 Array.prototype 上添加一个方法。看起来像是

No, not really. You don't have access to the array itself, your function only builds the compare-function that is later used when .sort is invoked on the array. If you needed to alter the array, you'll need to write a function that gets it as an argument; for example you could add a method on Array.prototype. It would look like

function mysort(arr) {
    // Preparation
    // declaration of compare function
    // OR execution of closure to get the compare function
    arr.sort(comparefn);
    return arr;
}




是否可以为闭包输入参数以便在PREPARATION STARTS和PREPARATION ENDS之间的代码可以使用它们?

Is it possible to input arguments to the closure so that code between PREPARATION STARTS and PREPARATION ENDS can use them?

是的,当然-这就是使用闭包的原因:- )但是,您不能在当前代码中使用 sortbyalphabet_timo(caseinsensitive)。您拥有的闭包将立即被调用(称为IIFE)并返回compare-function,您将像在演示中那样对它进行排序。

Yes, of course - that is the reason to use closures :-) However, you can't use sortbyalphabet_timo(caseinsensitive) with your current code. The closure you have is immediately invoked (called an IIFE) and returns the compare-function, which you pass into sort as in your demo.

如果要 sortbyalphabet_timo 要作为闭包而不是结果,您必须在其后删除括号。您还可以在其中使用参数,这些参数在整个闭包范围内都可以访问(包括comparefunction):

If you want sortbyalphabet_timo to be the closure instead of the result, you have to remove the brackets after it. You also you can use arguments there, which are accessible in the whole closure scope (including the comparefunction):

var sortbyalphabet_timo_closure = function(caseinsensitive) {
    // Preparation, potentially using the arguments
    // Declaration of compare function, potentially using the arguments
    return comparefn;
}
// then use
words.sort(sortbyalphabet_timo_closure(true));

当前,您正在执行以下操作:

Currently, you are doing this:

var sortbyalphabet_timo_closure = function(/*having no arguments*/) {
    // Preparation, potentially using the arguments
    // Declaration of compare function, potentially using the arguments
    return comparefn;
}
var sortbyalphabet_timo = sortbyalphabet_timo_closure();
// then use
words.sort(sortbyalphabet_timo);

…如果需要多次排序,它只是缓存执行闭包的结果。

…which just caches the result of executing the closure, if you'd need to sort multiple times.

这篇关于准备要排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆