关联数组与javascript中的对象 [英] associative array versus object in javascript

查看:88
本文介绍了关联数组与javascript中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的脚本中需要创建一个哈希表,我在谷歌搜索这个。大多数人都为此目的推荐JavaScript对象。问题是,哈希表中的一些键有。。在他们中。我可以使用关联数组轻松创建这些键。

In my script there is a need to create a hash table, i searched in google for this. Most of the folks are recommending JavaScript object for this purpose. Problem is, some of the keys in the hash table have "." in them. I am able to create these keys easily with the associative arrays.

我不明白为什么关联数组是坏的。在我看到的网站中提到的第一件事是长度属性。我来自Perl背景,我使用哈希。最常见的用途是从密钥中获取值,检查密钥是否存在,删除键值对,添加键值对。如果这些是我的常用用途,我可以安全地使用关联数组吗?

I don't understand why associative arrays are bad. First thing that is mentioned in the sites that i looked at is the length property. I am coming from the Perl background, where i used hashes. Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, add a key-value pair. If these are my common uses, can i safely use associative array?

推荐答案

在JavaScript中,对象是关联数组......对它们没有单独的概念。您还可以在密钥名称中安全地使用。,但只能使用括号表示法访问该值:

In JavaScript, Objects are Associative Arrays...there aren't separate concepts for them. You are also able to safely use '.' in a key name, but you can only access the value using the bracket notation:

var foo = {}
foo['bar'] = 'test';
foo['baz.bin'] = 'value';

alert(foo.bar); // shows 'test'
alert(foo['baz.bin']); // shows 'value'

如果您已经使用它们并且它们有效,那么您就安全了。

If you're using them already and they work, you're safe.

这篇关于关联数组与javascript中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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