Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中进行关联数组/哈希(How to do associative array/hashing in JavaScript)

I need to store some statistics using JavaScript in a way like I'd do it in C#:

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

Dictionary<string, int> statistics;

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

Is there an Hashtable or something like Dictionary<TKey, TValue> in JavaScript?

(JavaScript中是否有Hashtable或类似Dictionary<TKey, TValue>类的东西?)
How could I store values in such a way?

(如何以这种方式存储值?)

  ask by George2 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use JavaScript objects as associative arrays .

(使用JavaScript对象作为关联数组 。)

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

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

Create an object with

(创建一个对象)

var dictionary = {};

Javascript allows you to add properties to objects by using the following syntax:

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

Object.yourProperty = value;

An alternate syntax for the same is:

(相同的替代语法是:)

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..in循环构造遍历关联数组,如下所示)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...