我在使用 Array.prototype.sort()
时发现了一个奇怪的地方在一组数字上,我不确定是什么原因造成的。
我的目标是使用 sort
(而不是使用 reverse
)反转数组,这样我就可以像这样链接它:
const shouldReverse = Math.random() > 0.5,
result = foo().bar().map(...).reverseIf(shouldReverse);
我相信我应该能够使用 sort
来实现这一点,这似乎在某些情况下有效,但在其他情况下却无效。
这是一个工作示例:
const myArray = ['a', 'b', 'c', 'd'],
mySortedArray = myArray.sort(() => 1);
console.log(mySortedArray);
["d", "c", "b", "a"]
还有一个无效的例子:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'],
mySortedArray = myArray.sort(() => 1);
console.log(mySortedArray);
["f", "k", "a", "j", "i", "h", "g", "b", "e", "d", "c"]
这只发生在 Chrome 中,并且只有当数组中的元素超过 10 个时——这可能是 Chrome 的 V8 引擎中某种形式的优化吗?
最佳答案
I believe I should be able to achieve this using
sort
不,你不应该。您正在寻找reverse
.
对于已经按升序排序的特定示例,您可以通过传递导致降序的比较函数来实现反转,但这不适用于具有任意值的任意数组。
myArray.sort((a, b) => (a<b)-(b<a));
myArray.sort(() => 1)
那是一个 totally inconsistent comparison function .你不能指望它会起作用。
This only happens in Chrome and only when there are more than 10 elements in the array
这是因为 Chrome 中的 JS 引擎对小数组使用了不同的排序算法,它以不同的顺序进行比较,显然总是与第二个参数中索引较高的项进行比较。你真走运。
关于javascript - 在 Chrome 中使用 Array.prototype.sort 时数组的奇怪排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751432/