单项数组上的Array.sort()是否在不触发回调函数的情况下返回?
我正在利用 Array.sort() 对对象数组进行递归排序,每个对象都可能有子对象。
window.sortByrecent = function (a, b) {
if(a.children && !a.isSorted) {
a.children = a.children.sort(window.sortByrecent);
a.isSorted = true;
}
if(b.children && !b.isSorted) {
b.children = b.children.sort(window.sortByrecent);
b.isSorted = true;
}
// Later post comes first
return moment(b.date).unix() - moment(a.date).unix();
}
回答
您通常不应在.sort回调中排序(或执行副作用),因为:
- 元素相互比较的顺序可能取决于实现
- 如果副作用(例如排序子属性)很昂贵,那么您可能会不必要地执行比需要更多的次数。排序是一个
O(n log n)过程;你不需要对每个子数组进行排序log n,你只需要每 1 次排序。
你可能想要这样的东西:
const recursiveSort = arr => {
if (!arr.isSorted) {
arr.sort((a, b) => moment(b.date).unix() - moment(a.date).unix());
for (const { children } of arr) {
if (children) recursiveSort(children);
}
arr.isSorted = true;
}
};