简体   繁体   English

JavaScript 中的关联数组与对象

[英]Associative array versus object in JavaScript

In my script there is a need to create a hash table, and I searched in google for this.在我的脚本中需要创建一个哈希表,我在谷歌中搜索了这个。 Most of the folks are recommending JavaScript object for this purpose.大多数人都为此目的推荐 JavaScript 对象。 The The problem is some of the keys in the hash table have a "."问题是哈希表中的某些键有一个“.”。 in them.在他们之中。 I am able to create these keys easily with the associative arrays.我能够使用关联数组轻松创建这些键。

I don't understand why associative arrays are bad.我不明白为什么关联数组不好。 The first thing that is mentioned on the sites that I looked at is the length property.在我查看的网站上提到的第一件事是长度属性。

I am coming from the Perl background, where I used hashes.我来自 Perl 背景,在那里我使用了哈希。 Most common uses were to get the value from a key, check if a key exists, delete a key-value pair, and add a key-value pair.最常见的用途是从键中获取值、检查键是否存在、删除键值对以及添加键值对。 If these are my common uses, can I safely use an associative array?如果这些是我的常用用途,我可以安全地使用关联数组吗?

In JavaScript, objects are associative arrays...there aren't separate concepts for them.在 JavaScript 中,对象是关联数组……它们没有单独的概念。 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.如果您已经在使用它们并且它们有效,那么您就是安全的。

In a JavaScript, an object and array are pretty much the same thing, with an array having a bit of magical functionality (autoupdating the length property and such) and prototype methods suitable for arrays.在 JavaScript 中,对象和数组几乎是一回事,数组具有一些神奇的功能(自动更新长度属性等)和适用于数组的原型方法。 It is also much easier to construct an object than using an associative array:构造一个对象也比使用关联数组容易得多:

var obj = {"my.key": "myValue"};

vs.对比

var obj = [];
obj["my.key"] = "myValue";

Therefore never use the array object for this, but just the regular object.因此永远不要为此使用数组对象,而只是使用常规对象。

Some functionality:一些功能:

var obj = {}; // Initialized empty object

Delete a key-value pair:删除键值对:

delete obj[key];

Check if a key exists:检查密钥是否存在:

key in obj;

Get the key value:获取键值:

obj[key];

Add a key-value pair:添加键值对:

obj[key] = value;

Because there is no such thing as built-in associative arrays in JavaScript.因为 JavaScript 中没有内置关联数组这样的东西。 That's why it's bad.这就是为什么它很糟糕。

In fact, when you use something like:事实上,当你使用类似的东西时:

theArray["a"] = "Hello, World!";

It simply creates a property called "a" and set its value to "Hello, World!".它只是创建一个名为“a”的属性并将其值设置为“Hello, World!”。 This is why the length is always 0, and why the output of alert(theArray) is empty.这就是为什么长度总是 0,以及为什么alert(theArray)的输出是空的。

Actually, an "associative array" is pretty much the same as an "array-like object" in ECMAScript.实际上,“关联数组”与 ECMAScript 中的“类数组对象”几乎相同。 Even arrays are objects in ECMAScript, just with the exception to have numeric keys (which are still strings in the background) and a .length property, along with some inherited methods from Array.prototype .甚至数组也是 ECMAScript 中的对象,只是有数字键(它们仍然是后台的字符串)和.length属性,以及一些从Array.prototype继承的方法。

So, a Perl hash and an ECMAScript object behave similarly.因此,Perl 哈希和 ECMAScript 对象的行为相似。 You might not know that you can access object properties not only via a dot, but also with brackets and strings, like您可能不知道不仅可以通过点访问对象属性,还可以使用方括号和字符串访问对象属性,例如

var myObj = { foo: 42 };

myObj.foo; // 42
myObj['foo']; // 42

Knowing that, you can also use keys with .知道这一点,您还可以使用带有.

var myObj = { };
myObj['hello.foo.world'] = 42;

Of course, you can access that key only with the bracket notation.当然,您只能使用括号表示法访问该键。

You can use .您可以使用. in key names on JavaScript objects (AKA associative arrays) if you'd like;如果您愿意,可以在 JavaScript 对象(也称为关联数组)的键名中; they're accepted without issue.他们毫无问题地被接受。 The minor drawback is you can't use shortcut notations with the dotted keys, eg次要缺点是您不能使用带点键的快捷符号,例如

var x = {};
x['hello'] = 'there';
alert(x.hello);

is perfectly acceptable and will pop up an alert with 'there' in it.是完全可以接受的,并且会弹出一个带有“那里”的警报。 But if you use a dotted name:但是如果你使用带点的名字:

var x = {};
x['this.is'] = 'sparta';
alert(x.this.is);

will fail, as JavaScript will look for an attribute named this in the x object, which does not exist.将失败,因为 JavaScript 将在 x 对象中查找名为this的属性,该属性不存在。 There is only the this.is attribute.只有this.is属性。

There isn't an associative array.没有关联数组。 It's just an object.它只是一个对象。

foo.bar;    // Equivalent to...
foo["bar"]; // Looks like associative array.

For the sake of convenience of using data, there should be no difference between an object and an array.为了方便使用数据,对象和数组应该没有区别。 You can think of it as an object or you can think of it as an associative array.您可以将其视为一个对象,也可以将其视为一个关联数组。 At the end, you can just think of everything as data .最后,您可以将一切都视为数据

  • For PHP , [ ] accepts 0, 1, or more items(array), and it is called an associative array .对于 PHP ,[] 接受 0、1 或更多项(数组),它被称为关联数组 It is JSON in PHP's coat:它是 PHP 外衣中的 JSON:

    $data = ["message"=>[ "id"=>405, "description"=>"Method not allowed.", "detail"=>[]], "object" => []];

  • For JavaScript , { } accepts 0, 1, or more items(array), and it is called an object .对于 JavaScript , { } 接受 0、1 或更多项(数组),它被称为对象 This data format is JSON:此数据格式为 JSON:

    data = {"message": { "id":405, "description":"Method not allowed.", "detail" : {}}, "object" : {}};

I just call them data .我只是称它们为data The simplest way to describe data is JSON , or its variants.描述数据的最简单方法是JSON或其变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM