意外的不同结果 array.sort() Chrome / Edge

Unexpected different results array.sort() Chrome / Edge

这个 Javascript 代码使用 sort:

var items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros', value: 37 }
];

console.log(items.map(x=>x.name.toString()));

items.sort();

console.log(items.map(x=>x.name.toString()));

即使我们可以在 both browsers are compatible 中看到,结果也不同:

Google Chrome 63

["Edward", "Sharpe", "And", "The", "Magnetic", "Zeros"]
["Edward", "Sharpe", "And", "The", "Magnetic", "Zeros"]

微软边缘 25

["Edward", "Sharpe", "And", "The", "Magnetic", "Zeros"]
["Sharpe", "And", "The", "Magnetic", "Zeros", "Edward"]

知道是什么原因造成的或如何解决吗?

您可以在以下 JSBin

中测试此行为

Any idea of what is causing this

引自 MDN:

If [compareFunction is] omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

您的元素在这里是对象,因此它们的字符串转换将导致每个元素的字符串值 [object Object] - 因此您的每个项目都具有 相同的 比较值首先,none 个比另一个“小”或“大”。

所以你得到什么结果取决于浏览器实际使用的排序算法是否稳定。 (另见这个问题,什么是排序算法的稳定性,为什么它很重要? )

https://medium.com/@fsufitch/is-javascript-array-sort-stable-46b90822543f:

Well, nowhere in the ES7 specification does it say whether the sort needs to be stable or not. In fact, it tries to be super abstract, allowing as much of the sort to be “implementation defined” as possible. This has resulted in different JS engines (across different browsers) taking different routes to implementing this spec, leading to inconsistent sort stability behavior.

.

or how it could be resolved?

您需要实现自己的稳定排序算法。

但是您还需要使用自己编写的比较函数来正确比较您的对象,因为如前所述,您现在只比较 [object Object][object Object] ...