JavaScript Array.sort() 在 Firefox 中不起作用

Mor*_*ern 0 javascript firefox

假设我有一个要排序的数组,某个元素将排在第一位,其余部分保持原样。

例如 [1,2,3,4] 并且我希望 2 位于数组的开头

[1,2,3,4].sort((a,b)=> a == 2 ? -1 : 0)
Run Code Online (Sandbox Code Playgroud)

在 chrome 中,输出符合预期

// chrome
[2,1,3,4]
Run Code Online (Sandbox Code Playgroud)

但在 Firefox 中,输出不同,第 2 个不是第一个

// firefox
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 7

您还需要处理的案件均b2正确的:

 .sort((a, b) => (b === 2) - (a === 2))
Run Code Online (Sandbox Code Playgroud)

但在 Firefox 中,数组未排序

不完全是,Firefox 可能会使用不同的排序算法,以便以不同的顺序使用不同的参数调用排序器。如果以下条件始终为真,则数组仅在所有不同的实现中正确排序:

  sorter(a, a) === 0
  sorter(a, b) === - sorter(b, a)
Run Code Online (Sandbox Code Playgroud)

请注意,排序通常是 O(n log n) 平均情况(尽管如果很多元素相等可能会更好),而问题可以在 O(n) 中解决:

 const withoutTwo = array.filter(it => it !== 2);
 const result =
   Array.from({ length: array.length - withoutTwo.length }).fill(2)
    .concat(withoutTwo);
Run Code Online (Sandbox Code Playgroud)