我有一个应用程序,其中的对象用于显示用户系统上文件的 TreeView 。它的结构如下:
[{
text: 'C:/',
type: 'dir',
nodes: [
{
text: 'foo',
type: 'dir',
nodes: [] // And so on
},
{
text: 'bar',
type: 'file'
}
}]
根据惯例,我希望首先显示目录,然后显示文件。不幸的是,无论项目类型如何,我的数据都是按字母顺序检索的。
为了解决这个问题,我编写了一个很好的递归函数
var sort = function (subtree)
{
subtree = _.sortBy(subtree, function (item)
{
if (item.nodes)
{
sort(item.nodes)
}
return item.type
});
}
var tree = someTreeData;
sort(tree);
我使用 lodash 按文件类型的字母顺序对每个 nodes
数组进行排序。不幸的是,子树似乎没有引用树对象,因为当我记录其输出时,它仍然未排序。我该如何解决这个问题?
最佳答案
您可以使用JavaScript的内置Array.prototype.sort
函数,它可以就地排序。它接受两个参数并执行比较。请注意,在 sortBy
键提取器内对 item.notes
进行排序是不合适的。
function isDirectory(node) {
return !!node.nodes;
}
function sortTree(subtree) {
subtree.sort(function (a, b) {
return a.type < b.type ? -1 :
a.type > b.type ? 1 : 0;
});
subtree
.filter(isDirectory)
.forEach(function (node) {
sortTree(node.nodes);
});
}
关于javascript - 在递归函数中保留对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31554525/