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

Dictionary<string, int> statistics;

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

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


当前回答

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

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

其他回答

在c#中,代码如下:

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

or

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"]);
var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

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

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

由于JavaScript中的每个对象都像哈希表一样,并且通常是作为哈希表实现的,所以我就这样…

var hashSweetHashTable = {};
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;
    }
}