Javascript does not support an Associative array, but as all arrays in JavaScript are objects, JavaScript’s object syntax helps in imitating an Associative array.
var arr = {key1:'value1', key2:'value2'}
Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.
JavaScript associative array
Simple example code.
Note: myArray['a'] = 200;
is identical to myArray.a = 200;
!
<!DOCTYPE html>
<html>
<body>
<script>
var myArray = []; // Creating a new array object
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray)
console.log(typeof(myArray))
</script>
</body>
</html>
Output:
This is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it’s important to understand that this differs slightly from what you did. myObj instanceof Array
will return false
, because myObj
is not an ancestor from Array
in the prototype chain.
Source: stackoverflow.com
Another example
// Creating an empty "associative array" using an object
var myArray = {};
// Adding key-value pairs to the "associative array"
myArray['name'] = 'John';
myArray['age'] = 25;
myArray['city'] = 'New York';
// Accessing values in the "associative array"
console.log(myArray['name']); // Output: John
console.log(myArray['age']); // Output: 25
console.log(myArray['city']); // Output: New York
In this example, we use an object myArray
to simulate an associative array. We assign values to the object properties using square brackets notation, where the keys are strings (‘name’, ‘age’, ‘city’).
Comment if you have any doubts or suggestions on this JS Array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version