如何在JavaScript中进行关联数组/散列 [英] How to do associative array/hashing in JavaScript

查看:111
本文介绍了如何在JavaScript中进行关联数组/散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript计算/存储一些统计信息,C#中的等效代码在下面(我需要的功能是 - 键值对,字符串/ int键值对,按键操作值等),任何想法如何在JavaScript中实现相同的功能?看来没有内置的Dictionary或Hashtable?

 字典< 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆