There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array
is very different from a JavaScript Array
.
In PHP, an associative array can do most of what a numerically-indexed array can (the array_*
functions work, you can count()
it, etc.). You simply create an array and start assigning to string indexes instead of numeric.
In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will affect its length
, and can be iterated over using Array methods (map
, forEach
, reduce
, filter
, find
, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:
array['Main'] = 'Main Page';
is actually equivalent to:
array.Main = 'Main Page';
From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array
), and name based on what it should contain (e.g. pages
). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object
methods (Object.keys
in this case -- there's also entries
and values
being added to some browsers right now) which we can loop.
// Assigning values to corresponding keys
const pages = {
Main: 'Main page',
Guide: 'Guide page',
Articles: 'Articles page',
Forum: 'Forum board',
};
Object.keys(pages).forEach((page) => console.log(page));
associative arrays
in JS: it's either plain Array or an Object. Nothing prevents adding non-numeric properties toArray
, but that doesn't make itassociative
- in particular,length
property won't auto-count these properties. – Kelpie