Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - short way of declaring an associative array

Is there a short way of declaring an associative array like in PHP?

$myArray = array('a' => 'b'); // PHP Way 

In JavaScript I'd do it this way:

var myArray = []; myArray['a'] = 'b'; 

I'm not looking for JavaScript objects.

like image 631
js-coder Avatar asked Jul 31 '11 15:07

js-coder


People also ask

How do you write associative array in JavaScript?

An associative array is declared or dynamically createdWe can create it by assigning a literal to a variable. var arr = { "one": 1, "two": 2, "three": 3 }; Unlike simple arrays, we use curly braces instead of square brackets. This has implicitly created a variable of type Object.

What is are the ways for declaring associative array?

There are two ways to loop around the associative array. First, by using the for loop, and then by using the 'foreach' command. Example: In Associative arrays in PHP, the array keys() function is used to find indices with names provided to them, and the count() function is used to count the number of indices.

What is associative array in JavaScript?

Associative arrays are basically objects in JavaScript where indexes are replaced by user defined keys. They do not have a length property like normal array and cannot be traversed using normal for loop. Following is the code for associative arrays in JavaScript −

How do you declare an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


2 Answers

Declare an object like this:

var myArray = {"a": "b", "c": "d"}; 

... and then refer to each item like this:

var somethingElse = myArray["a"]; //Sets "somethingElse" to "b". 

As @Chris and @Marc mention in the comments: in JavaScript, objects ARE associative arrays, and vice versa, they just refer to two different ways of doing the same thing. For Example...

var somethingElse = myArray["a"]; var anotherVariable = myArray.a; 

... do the same thing.

like image 187
Karl Nicoll Avatar answered Sep 20 '22 06:09

Karl Nicoll


JavaScript does not have associative arrays. In your example, you declare myArray as array but then you assign an object to it. So your code is not different from this:

var myObject = {}; myObject['a'] = 'b'; 

Update: A little correction. Actually, the original code does not destroy the array. It just appends a regular property to it. That's possible because JavaScript arrays are a subset of JavaScript objects.

like image 37
Álvaro González Avatar answered Sep 21 '22 06:09

Álvaro González