算法的JavaScript"排序()"功能算法、功能、JavaScript、QUOT

2023-09-11 01:45:21 作者:ッ琉璃之瞳わ

最近,当我正与JavaScript的排序()函数,我发现的教程 1这个功能确实的数字不正确排序。代替进行排序的数字,一个功能必须指出,比较数字,像下面code: -

Recently when I was working with JavaScript "sort()" function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbers, a function must be added that compares numbers, like the following code:-

<script type="text/javascript">
function sortNumber(a,b)
{
    return a - b;
}

var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script>

输出则当属: -

The output then comes as:-

1,5,10,25,40,100

现在我不明白的是,为什么会发生这种情况与放大器;有谁能够告诉的细节是什么类型的算法在这个的sort()功能正在使用?这是因为,任何其他语言,我没有发现这个问题,即功能没有的正确的的数字进行排序。

Now what I didn't understand is that why is this occurring & can anybody please tell in details as to what type of algorithm is being used in this "sort()" function? This is because for any other language, I didn't find this problem where the function didn't sort the numbers correctly.

任何帮助是极大的AP preciated。

Any help is greatly appreciated.

推荐答案

那么,如果要排序下面的列表,它仅包含字符串:

Well, if you are sorting the following list, it contains only strings:

var n = ["10", "5", "40", "25", "100", "1"];

所以,我希望的任意的语言会比较它们作为字符串,从而导致的排序顺序:

So I would expect any language would compare them as strings, thus resulting in a sort order of:

var n = ["1", "10", "100", "25", "40", "5"];

这需要你的code使用自定义排序(如您已完成)投字符串返回整数进行排序的目的。

Which necessitates your code to use a custom sort (as you have done) to cast the strings back to integers for the purposes of sorting.

修改

由于尖提到的,默认情况下, JavaScript的sort()方法按字母顺序排序的元素,包括数字:

As Pointy mentioned, by default the JavaScript sort() method sorts elements alphabetically, including numbers:

默认情况下,sort()方法按字母顺序排序的元素和上升。然而,数字不会正确地排序(40到达前5)。要排序数字,必须添加的比较数字功能。

By default, the sort() method sorts the elements alphabetically and ascending. However, numbers will not be sorted correctly (40 comes before 5). To sort numbers, you must add a function that compare numbers.

简直太神奇了......所以自定义排序是整数数组甚至是必需的。

Simply amazing... so a custom sort is required even for an array of integers.