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.
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.
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.
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 −
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With