最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript set value to Associative Arrays - Stack Overflow

programmeradmin2浏览0评论

how set value in javascript to Associative Arrays?

Why in this case i get error: "car[0] is undefined"

var car = new Array();
car[0]['name'] = 'My name';

how set value in javascript to Associative Arrays?

Why in this case i get error: "car[0] is undefined"

var car = new Array();
car[0]['name'] = 'My name';
Share Improve this question asked Feb 3, 2011 at 13:43 user319854user319854 4,11614 gold badges43 silver badges45 bronze badges 2
  • Please not that "associative arrays" are just plain objects and that you should not use new Array() due its ambiguity. – Felix Kling Commented Feb 3, 2011 at 14:02
  • I did not think of that... @user319854, did you actually want to have car be the associative array? as in var car = {name:'My name'}; maybe? – user207968 Commented Feb 3, 2011 at 14:08
Add a ment  | 

4 Answers 4

Reset to default 9

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).

发布评论

评论列表(0)

  1. 暂无评论