为什么这种 Array.sort 行为在 Chrome 和 Node.js 中有所不同 [英] Why is this Array.sort behaviour different in Chrome vs Node.js
问题描述
让我们制作一个基本列表并对其进行排序,以确保 2
始终是列表中的第一个.够简单了吧?
Let's make a basic list and sort it to make sure that 2
is ALWAYS first in the list. Simple enough, right?
[1, 2, 3].sort((a, b) => {
if (a === 2) return -1;
return 0;
});
Chrome 结果:✓
Chrome result: ✓
[2, 1, 3]
节点结果:X
[1, 2, 3]
为了在 Node 中获得这种行为,你可以 - 很奇怪 - 查看 b
参数,如果它是 2
,则让它返回 1:
In order to get this behaviour in Node, you could - weirdly enough - look at the b
parameter and make it return 1 if it's 2
:
[1, 2, 3].sort((a, b) => {
if (b === 2) return 1;
return 0;
});
使用此实现,您会得到相反的结果;Chrome 将为 [1, 2, 3],Node 将为 [2, 1, 3].
With this implementation you get the opposite result; Chrome will be [1, 2, 3] and Node will be [2, 1, 3].
您对这种行为有合理的解释吗?我的排序功能在概念上有缺陷吗?如果是这样,您将如何编写这种排序行为?
Do you have a logical explaination for this behaviour? Is my sorting function conceptually flawed? If so, how would you write this sorting behaviour?
推荐答案
您对这种行为有合理的解释吗?
Do you have a logical explaination for this behaviour?
浏览器使用不同的排序方法.因此,他们可能以不同的顺序使用不同的参数调用提供的回调.如果您的排序功能不一致,排序将不稳定.这将导致错误的排序顺序(对于不同的输入数组也总是如此,因此您的排序永远不会真正起作用).
Browsers use different sorting methods. Therefore they possibly call the provided callback with different arguments in a different order. If your sort function is not consistent, the sorting won't be stable. This will lead to a wrong sort order (it also always would with different input arrays, so your sorting will never really work).
如果是这样,你会如何编写这种排序行为?
If so, how would you write this sorting behaviour?
确保这两个条件适用于所有可能的输入:
Make sure that these two conditions apply to every possible input:
1) 两个相等的元素不应排序:
1) Two equal elements should not be sorted:
sort(a, a) === 0
2) 如果 sort 函数被以相反的顺序调用,结果也是相反的:
2) If the sort function gets called in inversed order, the result is also inversed:
sort(a, b) - sort(b, a) === 0
在你的情况下,两者都没有填满:
In your case, both are not fullfilled:
sort(2, 2) // 1 -> wrong!
sort(2, 3) - sort(3, 2) // 1 -> wrong!
要编写稳定的排序,您必须查看a
和 b
:
To write a stable sort, you have to look at a
and b
:
function(a, b) {
if(a === 2 && b === 2)
return 0;
if(a === 2)
return 1;
if(b === 2)
return -1;
return 0;
}
或者把它缩短:
(a, b) => (a === 2) - (b === 2)
这篇关于为什么这种 Array.sort 行为在 Chrome 和 Node.js 中有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!