关于javascript中数组排序方法的困惑点 [英] Confusing point about Array sort method in javascript

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

问题描述

我想知道当像下面这样指定自定义排序功能时,javascript数组排序方法如何工作:

i was wondering how javascript Array sort method works, when a custom sorting function is specified like the one below :

arr = [1, 5, 122, 12];
arr.sort(function (a,b){return a-b;});

如果它只接受 arr中的两个参数a,b(1,5),我知道javascript允许的参数比函数中指定的参数多。但是排序函数的作用方式是,先比较1,5,再比较122,12,将结果存储在一个地方,然后重做比较。

if it only accepts two arguments a,b (1,5) in "arr", i know that javascript allow more arguments than those specified in the function. but how sort function is acting, does it compares 1,5 then 122,12, store result in a place then redo the comparison.

推荐答案


指定了自定义排序功能

when a custom sorting function is specified

这是不正确的。您提供用于比较项目的函数

This is not correct. You provide a function to compare items:


arr.sort()
arr.sort(compareFunction)

compareFunction

指定定义排序顺序的功能。如果省略,则
数组将根据每个字符的Unicode代码点
值(根据每个元素的字符串转换)进行排序。

Specifies a function that defines the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

排序算法本身在本机实现中进行了硬编码,无法更改。实现甚至可以根据数据类型或数组长度选择不同的算法。

The sort algorithm itself is hard-coded in native implementation and cannot be changed. Implementations may even choose to pick different algorithms depending on data types or array length.

基本原理是您可能有不同的需求:

The rationale is that you may have different needs:


  • 您可能想使用二进制排序规则,使 A a ,或者您可能想使用西班牙语排序规则,使 a á相同。

  • You may want to use binary collation and make A different from a or you may want to use Spanish collation and make a identical to á.

您可能要对自定义对象进行排序:

You may want to sort custom objects:

[
    {
        city: "Madrid",
        population: 4000000
    },
    {
        city: "Cairo",
        pages: 15000000
    }
]


  • 或者您可能想对水果进行排序并制成先于苹果:)

    但是,排序算法本身(快速排序等)是一种实现细节,通常对您的业务逻辑无关紧要。

    However, the sort algorithm itself (quicksort, etc.) is an implementation detail that normally doesn't matter for your business logic.

    这篇关于关于javascript中数组排序方法的困惑点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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