jquery - 按级别访问数组

jquery - Access array by level

假设我有下面这个数组:

['uploads']
    {
        ['file_1']
            {
                //maybe some attributes here
            }
        ['file_2']
            {
                //maybe some attributes here
            }
        ['folder_1']
            {
                ['file_1']
                    {
                        //maybe some attributes here
                    }
                ['file_2']
                    {
                        //maybe some attributes here
                    }
                ['folder_1']
                    {
                        ['file_1']
                            {
                                //maybe some attributes here
                            }
                        ['file_2']
                            {
                                //maybe some attributes here
                            }

                    }
            }
        ['folder_2']
            {
                ['file_1']
                    {
                        //maybe some attributes here
                    }
                ['file_2']
                    {
                        //maybe some attributes here
                    }
            }
    }

假设这个数组或对象称为数据。我认为 ['uploads'] 是一级;因此到目前为止,一级只有一个条目。 ['uploads'] 的第 2 层有 4 个条目、2 个文件和 2 个文件夹。如果一个条目是一个文件夹,它可以有更多的层次,你明白了。

然后所有这些都在 jquery 中创建为页面上的可点击 div。当然只有第一层。

因此,如果用户单击 folder_1,我想用 ['uploads'] 第二级的 folder_1 填充另一个名为 'current_directory' 的数组,如下所示: current_directory = data['uploads']['folder_1'];。然后这个数组被创建为可点击的 div,用户可以再次点击某个东西,如果它是一个文件夹,它将用新文件夹重新填充 current_directory,但这次如下:current_directory = current_directory['folder_1']; 或以任何一个为准用户点击的文件夹。

当我想回到上一个目录时,问题就来了。我如何跟踪我所在的级别或诸如签入数据(这是整个文件夹结构)数组 current_directory 属于哪个键(文件夹)之类的东西。

只是想你应该知道,在同一层级的任何2个键,无论是文件还是文件夹,都不能同名。然后文件和文件夹显然不会被称为 file_1 和 folder_1,而是用户生成的名称。

哦,然后,我所说的属性是指只有文件才能拥有的更多键,例如 ['type'] 和 ['size'].

你要做的事情通常是用stack数据结构做的:

例如查看简单的实现:

// create a stack named history
var history = []

// ...

// when a folder is expanded - add it to the stack
history.push(currentfolder)

// when going back - remove the last item
history.pop()
var current = history[history.length - 1]

因此,我们的想法是跟踪所有操作,并简单地 "undo" 最后一个操作;当前文件夹始终作为数组的最后一项进行访问。

要了解更多信息,请参阅文章 How do you implement a Stack and a Queue in JavaScript?