如何在JavaScript中进行关联数组/哈希

JavaScript

猴子蛋蛋

2020-03-12

我需要使用JavaScript来存储一些统计信息,就像在C#中那样:

Dictionary<string, int> statistics;

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

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

第986篇《如何在JavaScript中进行关联数组/哈希》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
路易番长 2020.03.12

You can create one using like the following:

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)

小卤蛋猿阿飞 2020.03.12

由于JS中的每个对象的行为都像-并且通常实现为-哈希表一样,所以我就这么做了...

var hashSweetHashTable = {};
神无老丝Davaid 2020.03.12

如果您要求键必须是任何对象,而不仅仅是字符串,那么可以使用我的jshashtable

MandyJinJin路易 2020.03.12
var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";

如果您来自面向对象的语言,则应查阅本文

Mandy古一 2020.03.12

因此在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中,我们可以使用hasOwnPropertylike

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

使用JavaScript对象作为关联数组

关联数组:简单来说,关联数组使用String而不是Integer数字作为索引。

创建一个对象

var dictionary = {};

Javascript允许您使用以下语法向对象添加属性:

Object.yourProperty = value;

相同的替代语法是:

Object["yourProperty"] = value;

If you can also create key to value object maps with the following syntax

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

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

You can iterate through an associative array using the for..in loop construct as follows

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android