JS 在 Firefox 和 Chrome 中排序不同的行为

JS sort different behaviour in Firefox and Chrome

我在 Chrome 和 Firefox 中都是 运行 基本排序,我看到了两个不同的结果。 Firefox 似乎忽略了值。

const data = [
  {
    "id": "a"
  },
  {
    "id": "b"
  },
  {
    "id": "c"
  },
  {
    "id": "d"
  },
  {
    "id": "e"
  },
  {
    "id": "f"
  },
  {
    "id": "g"
  },
  {
    "id": "h"
  }
]

const sorted = data.slice().sort((project) => {
  console.log(project.id)
  return project.id === 'h' ? -1 : 0;
})

console.log(sorted[0].id === 'h');

结果:

Firefox - false

Chrome - true

Firefox 中有错误吗?

不同的浏览器使用不同的排序算法。这会影响数组中的哪些订单元素将被传递到您传递给 sort().

的回调函数中

回调函数接受 两个 个参数(正在比较的两个值)并且应该 return 一些东西来指示它们是否相同或应该是哪个第一.

sort( function (a, b) { return 1 || 0 || -1 } )

当且仅当它被传递到 a.

时,您的代码才会将 "h" 排序到数组的开头

如果排序算法将它传递给 b,那么您将把它留在原处。

Is there a bug in Firefox?

没有。 specification 表示:

If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the sort order is implementation-defined.

换句话说,如果您没有提供适当的比较功能,那么生成的顺序可能会因浏览器而异。

进一步解释什么是一致性比较函数。除其他事项外,它指定以下内容需要成立:

a = a (reflexivity)

但是您的比较功能并非如此。因为你忽略了第二个参数,如果{"id": "h"}和它自己比较,你也会return -1,说明这个元素比它自己小,违反了前面提到的规则。