What's the difference between objects and associated array in javascript?

六眼飞鱼酱① 提交于 2019-11-29 13:35:55

Not really, here's why:

var arr = new Array();
arr["foo"] = 100;
arr["bar"] = 200;
console.log(arr.length); // Prints 0.

Adding elements to an associative array should increase its length (IMO).

It looks and acts (somewhat) like an associative array because of syntactic sugar. What appear to be "array entries", however, are (just) object properties.

If you define "associative array" as a data structure that stores information as a collection of key-value pairs, then yes, JavaScript objects are associative arrays.

However, the phrase "associative array" is not generally used in the context of JavaScript, rather, we say "object". I'd suggest sticking to standard JS terminology to avoid misunderstandings.

Note that JS also has (non-associative) arrays, with elements accessed via numeric indexes. These are also objects and so allow non-numeric key properties, but this is generally considered bad practice.

There are no associative-arrays in JavaScript. Everything is object.

Certainly they are similar but associative-arrays in JavaScript are just objects.

Associative Array

In computer science, an associative array (also called a map or a dictionary) is an abstract data type composed of a collection of (key,value) pairs, such that each possible key appears at most once in the collection.

As far as I know objects in JavaScript match that definition.

Of course there is no unique "Associative Array" object, that's any different then any other normal object. So if you want associative array functionality use a javascript object.

However the following is a common piece of misinformation

There is no associative array in JavaScript

You should simply ignore these people, maybe try to convince them they are wrong.

My response is coming late, but I hope this can help people to understand this difference. I was reading this post and there isn't a satisfactory definition of an associative array. JavaScript doesn't have Associative Arrays. These are just objects that you can treat as associative arrays for convenience. In objects you store values as named properties, very similar to associative arrays in other programming languages. That's why you can access the properties like an associative array, but with methods associated to objects. You can test creating an object and try all the things you can do with an associative array, but you can't do all the methods of an array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!