javascript set value to Associative Arrays
how set value in javascript to Associative Arrays?
Why in this case i get error: "car[0] is undefined"
va开发者_Python百科r car = new Array();
car[0]['name'] = 'My name';
Because you never defined car[0]
. You have to initialize it with an (empty) object:
var car = [];
car[0] = {};
car[0]['name'] = 'My name';
Another solution would be this:
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'});
var car = [];
car.push({
'name': 'My name'
});
You are taking two steps at once: the item 0 in the car array is undefined. You need an object to set the value of the 'name' property.
You can initialize an empty object in car[0] like this:
car[0] = {};
There is no need to call the Array() constructor on the first line. This could be written:
var car = [];
and if you want to have an object in the array:
var car = [{}];
in your example, car[0]
is not initialized and it is undefined
, and undefined
variables cannot have properties (after all, setting an associative array's value means setting the object's method).
精彩评论