Javascript value for associative arrays

how to set value in javascript for associative arrays?

Why in this case I get the error: "car [0] - undefined"

var car = new Array(); car[0]['name'] = 'My name'; 
+4
source share
4 answers

Because you never defined car[0] . You must initialize it with a (empty) object:

 var car = []; car[0] = {}; car[0]['name'] = 'My name'; 

Another solution would be the following:

 var car = [{name: 'My Name'}]; 

or this one:

 var car = []; car[0] = {name: 'My Name'}; 

or this one:

 var car = []; car.push({name: 'My Name'}); 
+8
source
 var car = []; car.push({ 'name': 'My name' }); 
+3
source

You take two steps at the same time: element 0 in the array of cars is undefined. You need an object to set the value of the name property.

You can initialize an empty object in car [0] as follows:

 car[0] = {}; 

There is no need to call the constructor Array () on the first line. This could be written:

 var car = []; 

and if you want to have an object in an array:

 var car = [{}]; 
+1
source

in your example, car[0] not initialized and undefined , and undefined variables cannot have properties (after all, setting the value of an associative array means setting the method of the object).

0
source

Source: https://habr.com/ru/post/1338257/


All Articles