我需要使用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";

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

其他回答

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

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

使用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 */
}

在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"]);

除非你有特别的理由不这样做,否则就用一个普通的对象。JavaScript中的对象属性可以使用哈希表样式的语法引用:

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

foo和bar元素现在都可以被引用为:

hashtable['foo'];
hashtable['bar'];

// Or
hashtable.foo;
hashtable.bar;

当然,这意味着你的键必须是字符串。如果它们不是字符串,它们会在内部转换为字符串,所以它仍然可以工作。你的里程可能会有所不同。

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

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