javascript - 我需要解释 JS 如何处理排序?

标签 javascript node.js sorting

假设有数组

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);

返回 truefalse 计算结果为 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/

相关文章:

javascript - 我如何将此内容输出到文本区域?

javascript - 最佳实践 - DRY 违规 Rails <-> JavaScript

json - 在 Node 和 React 中使用 JSON 数据库

node.js - 如何使用 NODE.JS 运行 ethereumjs

javascript - 如何按数据属性对 div 顺序位置进行排序

JavaScript 对象成员

javascript - Angularjs根据屏幕尺寸响应式隐藏和显示

node.js - 如何在 Node 中接收SIP音频并将WAV流发送到Google语音识别API?

java - 按两个标准排序以获得最终结果

mysql - SQL按日期排序问题