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

后端 未结 5 538
醉梦人生
醉梦人生 2020-12-11 16:30

The Confusing discussion

In this question, there is a discussion on the concepts of associated array and object in javaScript which I got a bit confused.

In

相关标签:
5条回答
  • 2020-12-11 17:17

    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.

    0 讨论(0)
  • 2020-12-11 17:27

    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.

    0 讨论(0)
  • 2020-12-11 17:27

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

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

    0 讨论(0)
  • 2020-12-11 17:27

    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.

    0 讨论(0)
  • 2020-12-11 17:27

    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.

    0 讨论(0)
提交回复
热议问题