jquery - 按级别访问数组

时间:2015-05-17 15:59:53

标签: jquery arrays stack

假设我在下面有这个数组:

['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,我想填充另一个名为'current_directory'的数组,其中包含第二级['uploads']的folder_1,如下所示:current_directory = data['uploads']['folder_1'];。然后将此数组创建为可点击的div,用户可以再次点击某个内容,如果它是一个文件夹,它将使用新文件夹重新填充current_directory,但这次如下:current_directory = current_directory['folder_1'];或用户点击的任何文件夹上。

现在问题出现在我想回到上一个目录的时候。我怎么可能跟踪我所处的级别或类似于数据current_directory所属的密钥(文件夹)的签入数据(整个文件夹结构)。

以为你应该知道在同一级别中没有2个密钥,无论是文件还是文件夹都可以具有相同的名称。然后文件和文件夹显然也不会被称为file_1和folder_1,而是用户生成的名称。

哦,然后,我所说的属性就像更多的键只有文件可以有['type']和['size']。

1 个答案:

答案 0 :(得分:0)

您尝试做的事情通常是使用stack数据结构:

E.g。看到简单的实现:

// 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]

因此,我们的想法是对所有行动进行跟踪并简单地“撤消”最后一个行动;当前文件夹始终可以作为数组的最后一项访问。

要了解详情,请参阅文章How do you implement a Stack and a Queue in JavaScript?