javascript中的嵌套哈希表

时间:2012-02-17 19:56:28

标签: javascript jquery data-structures hash dictionary

我想用js创建以下数据结构:

folders字典:folder-id(guid) : ==> pages dictionary

pages数组:page-position(int) : ==> files dictionary

files字典:file-id(guid) : ==> file object

我想知道每个集合中有多少项目。

您如何建议我在JS中实现此功能?

我应该使用具有动态添加属性的数组或对象吗?

2 个答案:

答案 0 :(得分:2)

你可以写出来:

var folders = {
    'folder1-guid': [
        {'file1-guid': 'file1-content'},
        {'file2-guid': 'file1-content'}
    ]
};

或者,创建ObjectArray个实例并为其分配属性。

答案 1 :(得分:2)

按以下方式进行操作。

function HashTable() {
    var content = {};
    var count = 0;
    this.Add = function(key, value) {
        if (content.hasOwnProperty(key)) throw new Error("Key already exist");
        content[key] = value;
        count++;
    };
    this.Set = function(key, value) {
        if (!content.hasOwnProperty(key)) count++;
          content[key] = value;
    };
    this.Get = function(key) {
        if (!content.hasOwnProperty(key)) throw new Error("No such key");
        return content[key];
    };
    this.AllKeys = function() {
        var keys = [];
        for (a in content) {
            keys.push(a);
        }
        return keys;
    };
    this.Count = function() {
        return count;
    };
    this.Remove = function(key) {
        if (!content.hasOwnProperty(key)) throw new Error("No such key");
        delete content[key];
        count--;
    };
}


// Then you can use it as follows

var folders = new HashTable();
folders.Add(1, 10);
alert(folders.Count());
alert(folders.Get(1));
folders.Remove(1);
alert(folders.Count());

它为您提供了更严格的OOP方法。

修改

这可以确保您的密钥是唯一的,可以随时计算并接受整数和 字符串作为键。