假设有数组
let arr = [10, 12, 3, 2, 5, 1, 9, 7, 8, 9, 4];
试试这个
arr.sort((a, b) => a > b);
// Results: [1, 4, 3, 2, 5, 7, 8, 9, 9, 10, 12]
但是,使用这个
arr.sort((a, b) => a - b) ;
// Results: [1, 2, 3, 4, 5, 7, 8, 9, 9, 10, 12]
let arr = [10, 12, 3, 2, 5, 1, 9, 7, 8, 9, 4];
console.log(arr.sort((a, b) => a > b));
let arr1 = [10, 12, 3, 2, 5, 1, 9, 7, 8, 9, 4];
console.log(arr1.sort((a, b) => a - b));
最佳答案
这是一本很好的读物,可以帮助您理解 Array.sort()
作品
引用与您的问题相关的内容:
If compareFunction(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.
Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to an index lower than a, i.e. b comes first.
还有这个:
arr.sort((a, b) => a > b);
返回 true
或 false
计算结果为 1 或 0,从不返回 -1
因此,对于这个“不完整”的函数,结果取决于执行代码的引擎使用的排序算法
- rhino.js:10,12,3,2,5,1,9,7,8,9,4
- 蜘蛛猴:1,2,3,4,5,7,8,9,9,10,12
- v8:1,4,3,2,5,7,8,9,9,10,12
关于javascript - 我需要解释 JS 如何处理排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52593858/