简体   繁体   中英

Are associative arrays supported in Javascript?

I've looked around to see whether Javascript supports associative arrays and despite the fact that it clearly says that it doesn't, it seems to work anyway?

I'd love to know if anything has changed in the specifications and whether or not it's recommended to use them.

Sample code:

 var foo = new Array; foo["bar"] = "It works"; console.log(foo["bar"]);

You should use objects for that, they are first-class citizens in JavaScript:

var foo = {
    "bar": "It works"
};

console.log(foo.bar);
console.log(foo["bar"]);

In Javascript, foo["bar"] is semantically equivalent to foo.bar . But this is Javascript object, not associative array. As you can see, however, you can treat the object as associative array.

I've looked around to see whether Javascript supports associative arrays and despite the fact that it clearly says that it doesn't

Where did you see that it clearly stated that JavaScript does not support associative arrays?

Associative arrays--a collection of key/value pairs (also called maps, dictionaries, and many other names in various contexts)--are the fundamental datatype in Javascript. However, in JavaScript, they are called "objects".

However, given your sample code:

var foo = new Array;
foo["bar"] = "It works";

it seems you may be asking a slightly different question, which is "Can a JavaScript array contain properties (other than its numerically indexed ones)"?

The answer, as well documented, and covered in countless question here on SO, is "yes". The reason is that in JavaScript, arrays are a special type of object, so like all objects, they can have named properties.

whether or not it's recommended to use them.

If you mean is it recommended to hang named properties off a JavaScript array, opinions differ. You can take a look at this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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