Javascript Array.sort safari问题

Javascript Array.sort safari问题,javascript,arrays,sorting,Javascript,Arrays,Sorting,我有一个数组: var arr = [ {id: "d", sequence: 3}, {id: "c", sequence: 4}, {id: "b", sequence: 2}, {id: "a", sequence: 1}, {id: "e"} ]; 并希望按照以下逻辑对其进行排序: 不带序列的元素应位于第一位 其他应按降序排序 我的解决办法是: arr.sort(function(a, b) { if (!a.sequence || !b

我有一个数组:

var arr = [
    {id: "d", sequence: 3},
    {id: "c", sequence: 4},
    {id: "b", sequence: 2},
    {id: "a", sequence: 1},
    {id: "e"}
];
并希望按照以下逻辑对其进行排序:

  • 不带
    序列的元素应位于第一位
  • 其他应按降序排序
我的解决办法是:

arr.sort(function(a, b) {
  if (!a.sequence || !b.sequence) return 1;
  return b.sequence - a.sequence;
});
我希望有以下顺序:

[{id: "e"}, {id: "c", sequence: 4}, {id: "d", sequence: 3}, ...]
但在safari中,您会收到:

[
  {id: "c", sequence: 4}, 
  {id: "d", sequence: 3},
  {id: "b", sequence: 2},
  {id: "a", sequence: 1},
  {id: "e"}
]
为什么在Safari
{id:“e”}
中是最后一个元素,而在Chrome和Firefox中是第一个


谢谢你的进步

您的排序比较器没有执行您希望它执行的操作。如果希望缺少“sequence”属性意味着元素应该在具有该属性的元素之前,则返回值必须反映:

arr.sort(function(a, b) {
  if (("sequence" in a) && !("sequence" in b))
    return 1;
  if (("sequence" in b) && !("sequence" in a))
    return -1;
  if (!("sequence" in a) && !("sequence" in b))
    return 0;
  return b.sequence - a.sequence;
});
(这可能用更少的代码就可以完成;为了清晰起见,它是显式的。)重要的是,排序比较器函数总是为每一对元素(以任意顺序)返回一致的结果

您的现有代码在浏览器之间的行为不同,因为排序实现在运行时系统之间有所不同。

您可以像这样使用
#sort

  • 返回
    表达式的第一部分检查
    序列
    是否存在
  • 第二部分按降序排列
    arr
  • 请参见下面的演示:

    var arr=[{id:“d”,序列:3},{id:“c”,序列:4},{id:“b”,序列:2},{id:“a”,序列:1},{id:“e}];
    var结果=arr.sort(函数(a,b){
    返回+('sequence'在a)-+('sequence'在b)| | b.sequence-a.sequence
    });
    控制台日志(结果)
    
    。作为控制台包装{top:0;max height:100%!important;}
    始终返回
    1
    而不管这两个(或两者)中的哪一个没有
    。sequence
    属性无法工作,它不是一个属性。它在Chrome和Firefox中工作更为幸运。比Pointy短的代码是
    函数(A,b){return(b.sequence | | | | | | | | | | | | | | | | | | | | | | | 124。