gpt4 book ai didi

javascript - Array.sort safari 问题

转载 作者:行者123 更新时间:2023-12-04 00:56:13 27 4
gpt4 key购买 nike

我有数组:

var arr = [
{id: "d", sequence: 3},
{id: "c", sequence: 4},
{id: "b", sequence: 2},
{id: "a", sequence: 1},
{id: "e"}
];

并希望按照以下逻辑对其进行排序:

  • 没有sequence的元素应该放在第一个
  • 其他应按降序顺序排序。

我的解决方案是:

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 中它是第一个元素?

感谢提前!

最佳答案

你的排序比较器没有按照你说的去做。如果您希望缺少“序列”属性意味着元素应该在元素之前具有这样的属性,则您的返回值必须反射(reflect)出这一点:

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;
});

(这可能用更少的代码来完成;为了清楚起见,它是明确的。)重要的是,排序比较器函数始终为每对元素(以任何顺序)返回一致的结果。

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

关于javascript - Array.sort safari 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45676046/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com