首页 > 代码库 > JS - Array.prototype.sort(compare)

JS - Array.prototype.sort(compare)

 

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1; // a < b,a 在 b 前面
  }
  if (a is greater than b by the ordering criterion) {
    return 1; // a > b,a 在 b 后面
  }
  // a must be equal to b
  return 0; // a === b,并列排序,保持在源数组中的先后顺序
}

 

JS - Array.prototype.sort(compare)