This question already has an answer here:
这个问题在这里已有答案:
- How to sort an array of integers correctly 14 answers
- 如何正确排序整数数组14个答案
I'm trying to use JavaScript's sort function on arrays of numbers and sometimes it doesn't do anything:
我正在尝试在数字数组上使用JavaScript的排序函数,有时它不会做任何事情:
var a = [200,20].sort(); // [20,200]
var b = [200,21].sort(); // [200,21]
的jsfiddle
2 个解决方案
#1
4
Javascript sorts everything as strings (=alphabetically) by default. The string "200"
is less than the string "21"
. To sort as numbers you have to tell it so:
默认情况下,Javascript将所有内容排序为字符串(=字母顺序)。字符串“200”小于字符串“21”。要排序为数字,您必须告诉它:
[200,21].sort(function(a,b) { return a-b })
#2
0
Yep, this is the standard behaviour for "sort" because it perform "string" reordering. If you want to sort by number value you must pass a "compare" function to sort, like this:
是的,这是“排序”的标准行为,因为它执行“字符串”重新排序。如果要按数字值排序,则必须通过“比较”功能进行排序,如下所示:
[200,21].sort(function (a, b) {
return a-b;
})
// [21, 200]
The function must return 0 for identical value, n < 0 if a < b and n > 0 if a > b. For that reason, the difference is enough to provide sorting (assuming that you're not using huge numbers)
该函数必须为相同的值返回0,如果a b,则n> 0。因此,差异足以提供排序(假设您没有使用大数字) ,则n>
#1
4
Javascript sorts everything as strings (=alphabetically) by default. The string "200"
is less than the string "21"
. To sort as numbers you have to tell it so:
默认情况下,Javascript将所有内容排序为字符串(=字母顺序)。字符串“200”小于字符串“21”。要排序为数字,您必须告诉它:
[200,21].sort(function(a,b) { return a-b })
#2
0
Yep, this is the standard behaviour for "sort" because it perform "string" reordering. If you want to sort by number value you must pass a "compare" function to sort, like this:
是的,这是“排序”的标准行为,因为它执行“字符串”重新排序。如果要按数字值排序,则必须通过“比较”功能进行排序,如下所示:
[200,21].sort(function (a, b) {
return a-b;
})
// [21, 200]
The function must return 0 for identical value, n < 0 if a < b and n > 0 if a > b. For that reason, the difference is enough to provide sorting (assuming that you're not using huge numbers)
该函数必须为相同的值返回0,如果a b,则n> 0。因此,差异足以提供排序(假设您没有使用大数字) ,则n>