如何在JavaScript中使用关联数组/哈希表

608

我需要使用JavaScript存储一些类似于C#中的统计数据:

Dictionary<string, int> statistics;

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

在JavaScript中是否有类似HashtableDictionary<TKey, TValue>的东西?
我该如何以这种方式存储值?


2
JavaScript是一种弱类型语言,因此无法仅声明字符串或整数,只能声明一个变量并将其赋值为字符串或整数。 :D - Gordon Gustafson
你可能想要查看 xDict。http://jsfiddle.net/very/MuVwd/ 它是一个用Javascript编写的字符串=>任何内容的字典。 - Robert
这篇文章非常好地解释了Javascript中关联数组在底层是如何实现的。https://www.jayconrod.com/posts/52/a-tour-of-v8-object-representation - Shuklaswag
被接受的答案是在2009年编写的 - 它只支持字符串键。对于非字符串键,请使用Map或WeakMap,就像Vitalii的答案中所述 - ToolmakerSteve
11个回答

1
您可以创建一个如下所示的HTML标签:

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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接