How to create an associative array in literary javascript notation

I understand that in javascript there are no associative arrays , only objects .

However, I can create an array with string keys using bracket notation as follows:

 var myArray = []; myArray['a'] = 200; myArray['b'] = 300; console.log(myArray); //prints [a: 200, b: 300] 

so I want to do the same without using bracket notation

 var myNewArray = [a: 200, b: 300]; //getting error - Unexpected token: 

it doesn't work either

 var myNewArray = ['a': 200, 'b': 300]; //same error, why can I not create? 
+5
source share
5 answers

Javascript has no associative arrays, just objects. Even JS arrays are basically just objects, just with the special thing that property names are numbers (0,1, ...).

First look at your code:

 var myArray = []; // creating a new array object myArray['a'] = 200; // setting the attribute a to 200 myArray['b'] = 300; // setting the attribute b 300 

It is important to understand that myArray['a'] = 200; identical to myArray.a = 200; !

So, to start with what you want: You cannot create a javascript array and not pass any number attributes to it.

But this is probably not what you need! You probably just need a JS object, which basically matches an associative array, dictionary, or map in other languages: it maps strings to values. And this can be done easily:

 var myObj = {a: 200, b: 300}; 

But itโ€™s important to understand that this is a little different from what you did. myObj instance of Array will return false because myObj is not an ancestor from an array in the prototype chain.

+4
source

Do you want to use the object in this case

 var myObject = {'a' : 200, 'b' : 300 }; 

This answer refers to a more detailed explanation: How to do associative array / hashing in JavaScript ( http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/ )

+1
source

Well, you create an array that is actually an object.

 var arr = []; arr.map; // function(..) arr['map']; // function(..) arr['a'] = 5; console.log(arr instanceof Object); // true 

You can add fields and functions to arr . It does not "insert" them into the array, though (for example, arr.push(...) )

You can refer to object fields with the syntax []

+1
source

Arrays and objects are two different things.

For an object, you can do things like:

 var obj = { "property1": "value1" }; obj.property2 = "value2"; 

For arrays you have to do this:

 var arr = []; arr[0] = "value"; 
+1
source

You can use the card:

 var arr = new Map([ ['key1', 'User'], ['key2', 'Guest'], ['key3', 'Admin'], ]); var res = arr.get('key2'); console.log(res); // The value is 'Guest' 
0
source

All Articles