How to dynamically add elements to js array?

For example, we first created an empty array:

var mas = {}; 

and in the end got this:

 { "name1" : val1 "name2" : val2 "name3" : val3 } 

I tried to just write like this:

 mas.name1 = val1; 

does not exceed(

What to do ?

  • one
    Well, this is an object and not an array, besides, everything works: var mas = {}; mas.name1 = 5; console.log (mas); Object {name1: 5} - zb '
  • Yes, and really earned, somewhere else nakosyachil means. - Stanislav Dalinin February

1 answer 1

First, it is not an array, but a hash. Array: ['hi', 'i\'m', 'Doctor', 123];
Secondly, the value ( val1 ) must be enclosed in quotes: 'val1' . Without them there will be an error. Only numbers without quotes can and should be.