Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  37] [ 5]  / answers: 1 / hits: 168625  / 8 Years ago, sun, may 29, 2016, 12:00:00

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


However I can create an array with string keys using bracket notation like this:


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

So I want to do the exact same thing without using bracket notation:


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

This does not work either:


var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?

More From » arrays

 Answers
4

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


So look at your code first:


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

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


So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.


But this is probably not what you need! Probably you just need a JavaScript object, what 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.


[#61976] Friday, May 27, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katianatasham

Total Points: 293
Total Questions: 110
Total Answers: 103

Location: Saint Helena
Member since Mon, Jun 28, 2021
3 Years ago
katianatasham questions
Tue, Jul 20, 21, 00:00, 3 Years ago
Thu, Mar 18, 21, 00:00, 3 Years ago
Wed, Nov 25, 20, 00:00, 4 Years ago
Wed, Jun 24, 20, 00:00, 4 Years ago
Fri, May 15, 20, 00:00, 4 Years ago
;