質問

C#で行うようにJavaScriptを使用して統計を保存する必要があります:

Dictionary<string, int> statistics;

statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);

JavaScriptにHashtableまたはDictionary<TKey, TValue>などがありますか?
このような方法で値を保存するにはどうすればよいですか?

役に立ちましたか?

解決

JavaScriptオブジェクトを連想配列として使用します。

  

連想配列:単純な言葉では、連想配列は整数としてではなく文字列をインデックスとして使用します。

でオブジェクトを作成する

var dictionary = {};
  

Javascriptを使用すると、次の構文を使用してオブジェクトにプロパティを追加できます。

Object.yourProperty = value;

同じものの代替構文は次のとおりです。

Object["yourProperty"] = value;

次の構文でキーから値へのオブジェクトマップも作成できる場合

var point = { x:3, y:2 };

point["x"] // returns 3
point.y // returns 2
  

次のようにfor..inループ構造を使用して、連想配列を反復処理できます

for(var key in Object.keys(dict)){
  var value = dict[key];
  /* use key/value for intended purpose */
}

他のヒント

var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

オブジェクト指向言語を使用している場合は、この記事を確認してください。

特別な理由がない限り、通常のオブジェクトを使用してください。 JavaScriptのオブジェクトプロパティは、ハッシュテーブルスタイルの構文を使用して参照できます。

var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";

foo要素とbar要素の両方が、次のように参照できるようになりました。

hashtable['foo'];
hashtable['bar'];
// or
hashtable.foo;
hashtable.bar;

もちろん、これはキーが文字列でなければならないことを意味します。文字列ではない場合、内部的に文字列に変換されるため、YMMVでも動作する可能性があります。

最新のブラウザはすべて、javascript Map オブジェクトをサポートしています。オブジェクトよりもマップの使用が優れている理由はいくつかあります:

  
      
  • オブジェクトにはプロトタイプがあるため、マップにはデフォルトのキーがあります。
  •   
  • オブジェクトのキーは文字列であり、マップの任意の値にできます。
  •   
  • オブジェクトのサイズを追跡しながら、マップのサイズを簡単に取得できます。
  •   

例:

var myMap = new Map();

var keyObj = {},
    keyFunc = function () {},
    keyString = "a string";

myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

myMap.size; // 3

myMap.get(keyString);    // "value associated with 'a string'"
myMap.get(keyObj);       // "value associated with keyObj"
myMap.get(keyFunc);      // "value associated with keyFunc"

他のオブジェクトから参照されていないキーをガベージコレクションする場合は、マップではなく、WeakMap

JSのすべてのオブジェクトはハッシュテーブルのように振る舞うため、一般的にはハッシュテーブルとして実装されているので、そのまま使用します...

var hashSweetHashTable = {};

C#ではコードは次のようになります:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

または

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

JavaScriptで

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

C#辞書オブジェクトには、dictionary.ContainsKey()などの便利なメソッドが含まれています JavaScriptでは、hasOwnPropertyのように使用できます

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

キーを単なる文字列ではなくオブジェクトにする必要がある場合は、 jshashtable

オブジェクトキーマッピング、列挙機能(forEach()メソッドを使用)、クリアなどの問題を達成するために作成しました。

function Hashtable() {
    this._map = new Map();
    this._indexes = new Map();
    this._keys = [];
    this._values = [];
    this.put = function(key, value) {
        var newKey = !this.containsKey(key);
        this._map.set(key, value);
        if (newKey) {
            this._indexes.set(key, this.length);
            this._keys.push(key);
            this._values.push(value);
        }
    };
    this.remove = function(key) {
        if (!this.containsKey(key))
            return;
        this._map.delete(key);
        var index = this._indexes.get(key);
        this._indexes.delete(key);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);
    };
    this.indexOfKey = function(key) {
        return this._indexes.get(key);
    };
    this.indexOfValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.get = function(key) {
        return this._map.get(key);
    };
    this.entryAt = function(index) {
        var item = {};
        Object.defineProperty(item, "key", {
            value: this.keys[index],
            writable: false
        });
        Object.defineProperty(item, "value", {
            value: this.values[index],
            writable: false
        });
        return item;
    };
    this.clear = function() {
        var length = this.length;
        for (var i = 0; i < length; i++) {
            var key = this.keys[i];
            this._map.delete(key);
            this._indexes.delete(key);
        }
        this._keys.splice(0, length);
    };
    this.containsKey = function(key) {
        return this._map.has(key);
    };
    this.containsValue = function(value) {
        return this._values.indexOf(value) != -1;
    };
    this.forEach = function(iterator) {
        for (var i = 0; i < this.length; i++)
            iterator(this.keys[i], this.values[i], i);
    };
    Object.defineProperty(this, "length", {
        get: function() {
            return this._keys.length;
        }
    });
    Object.defineProperty(this, "keys", {
        get: function() {
            return this._keys;
        }
    });
    Object.defineProperty(this, "values", {
        get: function() {
            return this._values;
        }
    });
    Object.defineProperty(this, "entries", {
        get: function() {
            var entries = new Array(this.length);
            for (var i = 0; i < entries.length; i++)
                entries[i] = this.entryAt(i);
            return entries;
        }
    });
}


クラスのドキュメントHashtable

メソッド:

  • get(key)
    指定されたキーに関連付けられた値を返します。
    パラメータ:
    key:値を取得するキー。

  • put(key, value)
    指定された値を指定されたキーに関連付けます。
    パラメータ:
    value:値を関連付けるキー。
    remove(key):キーに関連付ける値。

  • clear()
    指定されたキーとその値を削除します。
    パラメータ:
    indexOfKey(key):削除するキー。

  • indexOfValue(value)
    すべてのハッシュテーブルをクリアし、キーと値の両方を削除します。

  • indexOf()
    追加順序に基づいて、指定されたキーのインデックスを返します。
    パラメータ:
    toString():インデックスを取得するキー。

  • entryAt(index)
    追加順序に基づいて、指定された値のインデックスを返します。
    パラメータ:
    index:インデックスを取得する値。
    注:
    この情報は配列のcontainsKey(key)メソッドによって取得されるため、オブジェクトを単にcontainsValue(value)メソッドと比較します。

  • forEach(iterator)
    指定されたインデックスのエントリを表すキーと値の2つのプロパティを持つオブジェクトを返します。
    パラメータ:
    iterator:取得するエントリのインデックス。

  • length
    ハッシュテーブルに指定したキーが含まれているかどうかを返します。
    パラメータ:
    keys:チェックするキー。

  • values
    ハッシュテーブルに指定した値が含まれているかどうかを返します。
    パラメータ:
    entries:チェックする値。

  • entryAt()
    指定された<=>。
    パラメータ:
    のすべてのエントリを繰り返します <=>:3つのパラメーターを持つメソッド:<=>、<=>、および<=>。ここで、<=>はエントリのインデックスを表します。

    プロパティ:

  • <=> <!>#8195;(読み取り専用
    ハッシュテーブル内のエントリの数を取得します。

  • <=> <!>#8195;(読み取り専用
    ハッシュテーブル内のすべてのキーの配列を取得します。

  • <=> <!>#8195;(読み取り専用
    ハッシュテーブル内のすべての値の配列を取得します。

  • <=> <!>#8195;(読み取り専用
    ハッシュテーブル内のすべてのエントリの配列を取得します。それらはメソッド<=>。

  • の同じ形式で表されます。
function HashTable() {
    this.length = 0;
    this.items = new Array();
    for (var i = 0; i < arguments.length; i += 2) {
        if (typeof (arguments[i + 1]) != 'undefined') {
            this.items[arguments[i]] = arguments[i + 1];
            this.length++;
        }
    }

    this.removeItem = function (in_key) {
        var tmp_previous;
        if (typeof (this.items[in_key]) != 'undefined') {
            this.length--;
            var tmp_previous = this.items[in_key];
            delete this.items[in_key];
        }

        return tmp_previous;
    }

    this.getItem = function (in_key) {
        return this.items[in_key];
    }

    this.setItem = function (in_key, in_value) {
        var tmp_previous;
        if (typeof (in_value) != 'undefined') {
            if (typeof (this.items[in_key]) == 'undefined') {
                this.length++;
            } else {
                tmp_previous = this.items[in_key];
            }

            this.items[in_key] = in_value;
        }

        return tmp_previous;
    }

    this.hasItem = function (in_key) {
        return typeof (this.items[in_key]) != 'undefined';
    }

    this.clear = function () {
        for (var i in this.items) {
            delete this.items[i];
        }

        this.length = 0;
    }
}

https://gist.github.com/alexhawkins/f6329420f40e5cafa0a4

var HashTable = function() {
  this._storage = [];
  this._count = 0;
  this._limit = 8;
}


HashTable.prototype.insert = function(key, value) {
  //create an index for our storage location by passing it through our hashing function
  var index = this.hashFunc(key, this._limit);
  //retrieve the bucket at this particular index in our storage, if one exists
  //[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ]  [ [k,v] ] ]
  var bucket = this._storage[index]
    //does a bucket exist or do we get undefined when trying to retrieve said index?
  if (!bucket) {
    //create the bucket
    var bucket = [];
    //insert the bucket into our hashTable
    this._storage[index] = bucket;
  }

  var override = false;
  //now iterate through our bucket to see if there are any conflicting
  //key value pairs within our bucket. If there are any, override them.
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      //overide value stored at this key
      tuple[1] = value;
      override = true;
    }
  }

  if (!override) {
    //create a new tuple in our bucket
    //note that this could either be the new empty bucket we created above
    //or a bucket with other tupules with keys that are different than 
    //the key of the tuple we are inserting. These tupules are in the same
    //bucket because their keys all equate to the same numeric index when
    //passing through our hash function.
    bucket.push([key, value]);
    this._count++
      //now that we've added our new key/val pair to our storage
      //let's check to see if we need to resize our storage
      if (this._count > this._limit * 0.75) {
        this.resize(this._limit * 2);
      }
  }
  return this;
};


HashTable.prototype.remove = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];
  if (!bucket) {
    return null;
  }
  //iterate over the bucket
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    //check to see if key is inside bucket
    if (tuple[0] === key) {
      //if it is, get rid of this tuple
      bucket.splice(i, 1);
      this._count--;
      if (this._count < this._limit * 0.25) {
        this._resize(this._limit / 2);
      }
      return tuple[1];
    }
  }
};



HashTable.prototype.retrieve = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];

  if (!bucket) {
    return null;
  }

  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      return tuple[1];
    }
  }

  return null;
};


HashTable.prototype.hashFunc = function(str, max) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    hash = (hash << 5) + letter.charCodeAt(0);
    hash = (hash & hash) % max;
  }
  return hash;
};


HashTable.prototype.resize = function(newLimit) {
  var oldStorage = this._storage;

  this._limit = newLimit;
  this._count = 0;
  this._storage = [];

  oldStorage.forEach(function(bucket) {
    if (!bucket) {
      return;
    }
    for (var i = 0; i < bucket.length; i++) {
      var tuple = bucket[i];
      this.insert(tuple[0], tuple[1]);
    }
  }.bind(this));
};


HashTable.prototype.retrieveAll = function() {
  console.log(this._storage);
  //console.log(this._limit);
};

/******************************TESTS*******************************/

var hashT = new HashTable();

hashT.insert('Alex Hawkins', '510-599-1930');
//hashT.retrieve();
//[ , , , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Boo Radley', '520-589-1970');
//hashT.retrieve();
//[ , [ [ 'Boo Radley', '520-589-1970' ] ], , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Vance Carter', '120-589-1970').insert('Rick Mires', '520-589-1970').insert('Tom Bradey', '520-589-1970').insert('Biff Tanin', '520-589-1970');
//hashT.retrieveAll();
/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '520-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '520-589-1970' ] ] ]
*/

//overide example (Phone Number Change)
//
hashT.insert('Rick Mires', '650-589-1970').insert('Tom Bradey', '818-589-1970').insert('Biff Tanin', '987-589-1970');
//hashT.retrieveAll();

/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '818-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '650-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

hashT.remove('Rick Mires');
hashT.remove('Tom Bradey');
//hashT.retrieveAll();

/* 
[ ,
  [ [ 'Boo Radley', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]


*/

hashT.insert('Dick Mires', '650-589-1970').insert('Lam James', '818-589-1970').insert('Ricky Ticky Tavi', '987-589-1970');
hashT.retrieveAll();


/* NOTICE HOW HASH TABLE HAS NOW DOUBLED IN SIZE UPON REACHING 75% CAPACITY ie 6/8. It is now size 16.
 [,
  ,
  [ [ 'Vance Carter', '120-589-1970' ] ],
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Dick Mires', '650-589-1970' ],
    [ 'Lam James', '818-589-1970' ] ],
  ,
  ,
  ,
  ,
  ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Ricky Ticky Tavi', '987-589-1970' ] ],
  ,
  ,
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]




*/
console.log(hashT.retrieve('Lam James'));  //818-589-1970
console.log(hashT.retrieve('Dick Mires')); //650-589-1970
console.log(hashT.retrieve('Ricky Ticky Tavi')); //987-589-1970
console.log(hashT.retrieve('Alex Hawkins')); //510-599-1930
console.log(hashT.retrieve('Lebron James')); //null

次のように作成できます:

var dictionary = { Name:"Some Programmer", Age:24, Job:"Writing Programs"  };

//Iterate Over using keys
for (var key in dictionary) {
  console.log("Key: " + key + " , " + "Value: "+ dictionary[key]);
}

//access a key using object notation:
console.log("Her Name is: " + dictionary.Name)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top