00 Votes

JavaScript: Create associative Arrays

Question by Guest | 2015-08-08 at 20:51

Up to now, I have only seen numeric or numbered indexes in JavaScript.

However, other languages such as PHP are also supporting associative arrays with named indexes. That is, you can not only access an array element using arr[0] but also using arr["name"] which can help avoiding confusing.

As I have said, in JavaScript I have never seen something like that. Of course, that do not have to mean that it is impossible. So, does someone know more about it? Is it possible to use associative arrays in JavaScript? And if so, how to create such arrays?

ReplyPositiveNegative
0Best Answer0 Votes

JavaScript does not support associative arrays. Arrays in JavaScript always have a numbered index.

However, instead of an array, you are free to declare an object and you can use the properties of this object instead of an array.

Let us have a look at the following array:

var arr = ["Martin", 38];

You can declare the information from this array as an object in the following way:

var obj = {name:"Martin", age: 38};

The elements can be accessed like that:

var a = arr[0];    // Martin
var b = arr[1];    // 38

var c = obj.name;  // Martin
var d = obj.age;   // 38

As usual, we are accessing the elements of the array via the index number. Apart from that, we can access the object via the properties .name and .age which is like getting an associative array in JavaScript although it is not a proper array at all.
2015-08-09 at 17:23

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.