如何在JavaScript中进行关联数组/散列 [英] How to do associative array/hashing in JavaScript
问题描述
字典< string,int>统计;
statistics [Foo] = 10;
statistics [Goo] = statistics [Goo] + 1;
statistics.Add(Zoo,1);
使用。
关联数组:简单的单词关联数组使用字符串而不是整型数字作为索引。
创建一个对象与
var dictionary = {};
Javascript允许您通过使用以下语法向对象添加属性:
Object.yourProperty = value;
另一种语法是:
Object [yourProperty] = value;
如果您还可以使用以下语法创建键值来对象映射
var point = {x:3,y:2}
point [x] // => 3;
point.y // => 2;
您可以使用for..in循环遍历关联数组构造如下
for(key in dict){
var value = dict [键];
/ *使用键/值用于预期目的* /
}
I want to calculate/store some statistics information using JavaScript, the equivalent code in C# is below (features I need are -- key-value pair, string/int key value pair, manipulate values by keys, etc.), any ideas how to implement the same function in JavaScript? Looks like there is no built-in Dictionary or Hashtable?
Dictionary<string, int> statistics;
statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);
Use JavaScript objects as associative arrays.
Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.
Create an object with
var dictionary = {};
Javascript allows you to add properties to objects by using the following syntax:
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"] // => 3;
point.y // => 2;
You can iterate through an associative array using the for..in loop construct as follows
for(key in dict){
var value = dict[key];
/* use key/value for intended purpose */
}
这篇关于如何在JavaScript中进行关联数组/散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!