我需要使用JavaScript存储一些统计数据,就像我在c#中做的那样:

Dictionary<string, int> statistics;

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

JavaScript中是否存在哈希表或Dictionary<TKey, TValue>之类的东西? 我如何以这种方式存储值呢?


当前回答

如果你需要你的键是任何对象,而不仅仅是字符串,那么你可以使用我的jshashtable。

其他回答

你可以像下面这样创建一个:

var字典={名字:“一些程序员”,年龄:24岁,工作:“编写程序”}; //使用键进行迭代 For (var key in dictionary) { console.log("Key: "+ Key + ", "+ "Value: "+ dictionary[Key]); } //使用对象表示法访问键: console.log(" she name is: " + dictionary.Name)

所有现代浏览器都支持JavaScript Map对象。有几个原因使得使用Map比使用Object更好:

Object有一个原型,所以映射中有默认键。 对象的键是字符串,它们可以是Map的任何值。 当你必须跟踪对象的大小时,你可以很容易地获得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而不是Map。

如果你需要你的键是任何对象,而不仅仅是字符串,那么你可以使用我的jshashtable。

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

如果你来自面向对象的语言,你应该看看这篇文章。

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;
    }
}