javascript 排序在不同浏览器上的歧义

javascript sort ambiguity on different browsers

我得到了相当标准的 JS 数组,类似于:

"entities": [
    {
      "id": "1111",
      "options": {
        "label": "Label",
        "choices": [
          {
            "value": "222222"
          },
          {
            "value": "444444"
          }
        ]
      }
    },
    {
      "id": "2222",
      "options": {
        "label": "Label",
        "choices": [
          {
            "value": "333333"
          },
          {
            "value": "555555"
          }
        ]
      }
    },
...

我得到的排序函数总是告诉我两个元素是相等的,看起来像这样:

function sortF(a,b){
    return 0;
}

现在我将实体数组排序为:

entities.sort(sortF);

没有变化是我在这里的预期行为,但结果在不同的浏览器上是不同的。例如在 IE 上它很好,但在 Chrome 上它以不同的顺序对数组进行排序。

在 MDN 上,我在排序描述下注意到了这一点,但不确定这是否相关:

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

我怎样才能让它在所有浏览器中都一样工作?如果我的排序函数说两个元素相等,我希望排序函数保持原样。

我建议使用自己的 属性 进行稳定排序:

entities.forEach(function (a, i) {
    a.origin = i;
});


function sortF(a, b){
    return a.origin - b.origin;
}

entities.sort(sortF);

结果,与原数组排序顺序相同的稳定排序