Javascript 控制台返回不正确的排序数组

标签 javascript arrays sorting

我在 chrome 控制台中输入了以下代码。

var array = [25,7,8,41];
array.sort();

它返回 [25,41,7,8]。怎么回事?

最佳答案

The sort() method sorts the items of an array.

The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).

By default, the sort() method sorts the values as strings in alphabetical and ascending order.

This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce an incorrect result when sorting numbers.

如果您希望更正此问题,您可以编写一个比较函数作为传递给排序方法的第一个参数。引用文献中列出了一个!

编辑:张贴在这里以备将来使用...

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

Reference

关于Javascript 控制台返回不正确的排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40029157/

相关文章:

javascript - 单击动态更改的元素上的按钮

javascript - Jquery数组循环

php in_array() 以数组为针产生意外结果

JavaScript 数组排序

对 RDLC 报告中的矩阵列进行排序

javascript - 向右滚动对象

javascript - 如何检测剪贴板是否可以在 Firefox 中访问?

python - 如何从 NumPy 数组中删除所有零元素?

c# - 有效地找到最近的字典键

JavaScript 编码字段而不破坏显示