Discuss / JavaScript / sort排序什么时候0才有用?

sort排序什么时候0才有用?

Topic source

玹帝

#1 Created at ... [Delete] [Delete and Lock User]

<pre><code>var arr = [10, 20, 1, 2, 1, 2]; arr.sort((x, y) => { return x>y? 1 : -1 }); console.log(arr);//[1, 1, 2, 2, 10, 20] </code></pre>

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

0的意思是相等,这个时候,排在前面的还是在前面,排在后面的就还在后面:

var arr = ['apple', 'APPLE', 'ZOO', 'zoo', 'Bear'];
arr.sort((s1, s2) => {
    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();
    if (s1 === s2) {
        return 0;
    }
    return s1 < s2 ? -1 : 1;
});

结果:

["apple", "APPLE", "Bear", "ZOO", "zoo"]

孙竹山

#3 Created at ... [Delete] [Delete and Lock User]

这么说这种sort()是一种稳定的排序了?可是官方文档介绍的时候,这么说

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

意思加上return 0;的情况就是稳定sort?


  • 1

Reply