1

JavaScriptのハッシュテーブル/辞書を説明する次の記事を検討してください。

誰かが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オブジェクトを設計することを考えた1つの方法は、次のようなものでした。

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; 関数がnullになっているため、値を取り戻すことはできません。

上記のいずれも発生しないため、setおよびget機能がディクショナリ自体ではなく内部オブジェクトに適用される必要があります。

4

1 に答える 1

2
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"
于 2012-08-29T10:27:58.730 に答える