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

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

问题描述

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

字典统计数据;统计[Foo"] = 10;统计["咕"] = 统计["咕"] + 1;统计.Add("动物园", 1);

JavaScript 中是否有 Hashtable 或类似 Dictionary 之类的东西?
我怎么能以这种方式存储值?

解决方案

使用 JavaScript 对象作为关联数组.

<块引用>

关联数组:简单来说,关联数组使用字符串而不是整数作为索引.

创建一个对象

var 字典 = {};

<块引用>

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

Object.yourProperty = value;

相同的替代语法是:

Object[yourProperty"] = value;

如果可以,还可以使用以下语法创建键值对象映射:

var point = { x:3, y:2 };point[x"]//返回 3point.y//返回 2

<块引用>

您可以使用 for..in 循环构造遍历关联数组,如下所示

for(var key in Object.keys(dict)){var value = dict[key];/* 将键/值用于预期目的 */}

I need to store some statistics using JavaScript in a way like I'd do it in 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?
How could I store values in such a way?

解决方案

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"] // 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 中进行关联数组/散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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