JS如何对数字进行排序?

5

我正在学习JavaScript,排序数字时遇到问题,不理解如何使用排序函数并找到了一种使用列表而非数组的其他排序方法,需要解释。 我还看到了这个链接:Sorting array with numbers without sort() method

const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b) {
  return a - b
});
document.getElementById("demo2").innerHTML = points;

document.getElementById("demo3").innerHTML = points.sort();
unsorted:
<div id="demo1"></div>
sorted:
<div id="demo2"></div>
sorted alphabetically:
<div id="demo3"></div>


4
不清楚你在问什么,或者在JS中列表和数组的含义是什么。如果你想知道如何编写排序函数,有很多参考资料可供使用。 - Dave Newton
你的代码可以直接使用。我已经添加了缺失的HTML代码片段,现在你可以自己看到效果了。 - Carsten Massmann
查看 MDN 上关于 Array.prototype.sort() 的资源,你就会理解回调函数的作用:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort 。如果你想了解排序算法的工作原理,那么也许你应该谷歌“冒泡排序”或“快速排序”。 - Carsten Massmann
1
我猜你是在说你不明白为什么需要排序函数。这是因为默认情况下,JavaScript将数组的元素转换为字符串,并根据UTF-16值对它们进行排序。即使您只有数字数组,它也会被转换并作为字符串进行比较。您应该阅读sort的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort - skyline3000
排序函数默认按字典顺序排序,除非您使用函数覆盖它。因此,在字典中,“a”在“aa”之前,在“b”之前等等。所以,“1”在“10”之前,但是“100”在“2”之前,就像“aa”在“b”之前一样。解决方案是强制将其作为数字进行比较。为此,您可以使用“-”运算符。要使用“-”运算符与.sort()一起使用,您需要执行points.sort((a,b) => a - b) - slebetman
1个回答

0

const points = [40, 100, 1, 5, 25, 10];

console.log(points)

console.log(points.sort())

console.log(points.sort(function(a, b){return (a - b);}))

默认情况下,sort()函数将值作为字符串进行排序。

然而,如果将数字作为字符串进行排序,"25"比"100"大,因为"2"比"1"大。

因此,当对数字进行排序时,sort()方法会产生不正确的结果。

您可以通过提供比较函数来解决这个问题:

const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b});

解决方案


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接