javascript 将值设置为关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4886834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript set value to Associative Arrays
提问by user319854
how set value in javascript to Associative Arrays?
如何将javascript中的值设置为关联数组?
Why in this case i get error: "car[0] is undefined"
为什么在这种情况下我收到错误:“汽车 [0] 未定义”
var car = new Array();
car[0]['name'] = 'My name';
回答by ThiefMaster
Because you never defined car[0]. You have to initialize it with an (empty) object:
因为你从来没有定义car[0]. 您必须使用(空)对象对其进行初始化:
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'});
回答by Bj?rn
var car = [];
car.push({
'name': 'My name'
});
回答by Eric Bréchemier
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.
您同时采取两个步骤:汽车数组中的项目 0 未定义。您需要一个对象来设置“名称”属性的值。
You can initialize an empty object in car[0] like this:
您可以像这样在 car[0] 中初始化一个空对象:
car[0] = {};
There is no need to call the Array() constructor on the first line. This could be written:
不需要在第一行调用 Array() 构造函数。这可以写成:
var car = [];
and if you want to have an object in the array:
如果你想在数组中有一个对象:
var car = [{}];
回答by gion_13
in your example, car[0]is not initialized and it is undefined, and undefinedvariables cannot have properties (after all, setting an associative array's value means setting the object's method).
在您的示例中,car[0]未初始化并且是undefined,并且undefined变量不能具有属性(毕竟,设置关联数组的值意味着设置对象的方法)。

