使用返回-1的compareFunction排序不能保证顺序

时间:2019-07-12 05:21:52

标签: javascript arrays

我想根据某种布尔条件对列表中的元素进行排序:如果为true,则将这些元素放在后面。因此,我将sortcompareFunction一起使用,如下所示: myArray.sort(elem => booleanCondition(elem) ? 1 : -1);

但是,对于elem给出值-1的testArray = ["first", "second", "third", "fourth"] console.log(testArray.sort(e => 1)) console.log(testArray.sort(e => 1)) console.log(testArray.sort(e => 1)) console.log(testArray.sort(e => 1)) > Array ["first", "second", "third", "fourth"] > Array ["first", "second", "third", "fourth"] > Array ["first", "second", "third", "fourth"] > Array ["first", "second", "third", "fourth"] ,顺序将在重复调用时发生变化。

我在这里尝试了一个简单的测试:

console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))
console.log(testArray.sort(e => -1))

> Array ["fourth", "third", "second", "first"]
> Array ["first", "second", "third", "fourth"]
> Array ["fourth", "third", "second", "first"]
> Array ["first", "second", "third", "fourth"]

但是:

sort

我希望顺序保持一致-类似于1排序的工作方式。它不必保留原始顺序,只需保持一致即可(因此它不会一直在我的前端:P上跳来跳去)

问题:将compareFunction与返回-1的{{1}}一起使用时,如何为元素赋予一致的顺序?

0 个答案:

没有答案