【问题标题】:JavaScript Hashtable / DictionaryJavaScript 哈希表/字典
【发布时间】:2012-08-23 20:16:31
【问题描述】:

请考虑以下解释 JavaScript 中的哈希表/字典的文章:

Can anyone recommend a good Hashtable implementation in Javascript?

鉴于接受的答案,我希望能够做到这一点:

var instance = new Dictionary();
instance['key1'] = 'Foo';
instance['key2'] = 'Bar';
instance['key3'] = 123;
instance['key4'] = true;

但我希望键/值对在内部指向字典中的对象。考虑以下代码结构

var Dictionary = function() {
    var dictionary; // <-- key value pairs should point to this, not to the Dictionary function;

    this.setValue = function(key, value) {
        dictionary[key] = value;
    }

    this.getValue = function() {
        return dictionary[key];
    }
}

这可能吗?

编辑:

我想到设计 Dictionary 对象的一种方式是这样的:

var Dictionary = function() {
    this.setValue = function(key, value) {
        this[key] = value;  
    }

    this.getValue = function(key) {
        return this[key];
    }
}

这样做的问题是:

  1. 我可以这样赋值 instance['key1'] = 'foo';并像这样读取 instance.key1;我不要这个!!

  2. 我可以分配这个实例['getValue'] = null;然后无法取回值,因为该函数现在为空!!

以上都不应该发生,因此设置和获取功能应该应用于内部对象,而不是字典本身。

【问题讨论】:

  • 为什么?为什么不只是var instance = {};
  • @JonHanna,因为 Dictionary 将是“强”(如果可以与 JS 一起使用)类型库的一部分,其中 Dictionary 将表示与 Java 或 C# 中类似的结构。将实例定义为 { } 会破坏库结构,因为 { } 也可以应用于任何其他对象类型。
  • 到目前为止,您已经描述了一个普通的 javascript 对象。由于所有对象都可以做到这一点,也许只需创建一个类型匹配的类型(如果有的话),就是这样?
  • @JonHanna 还有更多内容。第一个方面是“填充”任何未定义的“本机”js 对象。然后这些对象将被分配额外的功能,并使用继承模型形成层次结构。最后,像 Dictionary 这样的对象也将被添加到层次结构中。虽然我知道它是一个普通对象,但它必须继承其祖先的功能(并在必要时覆盖)并添加额外的功能。希望这是有道理的:-S
  • 我认为是这样,但您仍在添加它已经拥有的功能,这是我没有看到重点的地方。所有 javascript 对象都继承了成为字典的能力,那么您实际上添加的是什么?

标签: javascript ecmascript-5 jscript


【解决方案1】:
function Dictionary()
{
    this.store = {};    
    this.setValue = function(key, value) {
        store[key] = value;
    }
    this.getValue = function(key)
    {
        return store[key];
    }
    return this;
}
//Testing
var dict = Dictionary();
dict.setValue('key','value');
alert(dict.getValue('key'));//displays "value"
alert(dict.getValue('unassignedKey'));//displays "undefined"
alert(dict['key']);//displays "undefined" (an unfortunate lack of syntactic convenience, we have to go through getValue).
alert(dict.key);//displays "undefined"
var dict2 = Dictionary();
dict2.setValue('key2', 'value2');
alert(dict2.getValue('key'));//displays "undefined"
alert(dict2.getValue('key2'));//displays "value2"

【讨论】:

  • alert(dict['key']);//显示“未定义”(不幸的是缺乏语法便利,我们必须通过 getValue)...它到达那里...但是它仍然需要这个。我可能不得不保护函数不被覆盖!
  • 这需要您重载 [] 运算符,而这在 javascript 中是无法做到的。见stackoverflow.com/questions/1711357/…
  • 啊,这回答了我的问题!谢谢!
猜你喜欢
  • 2013-03-21
  • 2014-01-04
  • 1970-01-01
  • 2010-10-18
  • 2013-01-15
  • 2011-06-10
  • 2017-07-18
  • 2012-04-21
  • 1970-01-01
相关资源
最近更新 更多