繁体   English   中英

array.prototype.sort当前有不同的顺序吗?

[英]array.prototype.sort present has different order?

这是我的代码:

let arr = [
  { a: false, index: 1 },
  { a: true, index: 2 },
  { a: false, index: 3 },
  { a: true, index: 4 },
  { a: true, index: 5 },
]

arr.sort((a, b) => a.a && !b.a ? 1 : -1)

在Chrome中,返回

[
  {a: false, index: 1},
  {a: false, index: 3},
  {a: true, index: 2},
  {a: true, index: 4},
  {a: true, index: 5},
]

这是我的目标结果。

但是我在Safari中找到了相同的代码:

[
  {a: false, index: 3},
  {a: false, index: 1},
  {a: true, index: 5},
  {a: true, index: 4},
  {a: true, index: 2},
]

他们有不同的结果吗?

毕竟,我通过以下方式解决了这个问题:

arr.sort(
  (a, b) =>
    !a.a && b.a
      ? -1
      : a.a === b.a
        ? 0
        : 1
)

我无法获得差异?

浏览器具有sort不同实现。 如果需要的话,可以使用另一个排序/过滤器对其进行更多组织,或者更改当前的排序功能以也考虑索引。

排序算法很多,您可以将它们定义为两组:

稳定排序和不稳定排序

如果两个具有相同关键字的对象在未排序输入中出现的顺序相同,则排序算法被认为是稳定的。 但是,如果有两个或多个对象具有相同的键,而排序前后的顺序不同,则排序算法就不稳定。

由于ECMAScript Array.prototype.sort未定义平台应实施的算法,因此Safari和Chrome仅使用不同的算法。

V8 (Chrome)对小数组(最多10个元素)使用插入排序,对大数组使用快速排序(不稳定的排序),Safari仅使用不同的排序算法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM