[英]how to create, assign and access new values to object?
How to create, assign and access new values to object ? 如何创建,分配和访问对象的新值?
Declaring new objects and adding new values to is is problem for me. 声明新对象和添加新值对我来说是个问题。
can any one help me? 谁能帮我?
var Countries = [
{
name : 'USA',
states : [
{
name : 'NH',
cities : [
{
name : 'Concord',
population : 12345
},
{
name : "Foo",
population : 456
}
/* etc .. */
]
}
]
},
{
name : 'UK',
states : [ /* etc... */ ]
}
]
Tried like this: 尝试这样:
Countries = new Array();
Countries[0] = new Country("USA");
Countries[0].states[0] = new State("NH");
Countries[0].states[0].cities[0] = new city("Concord",12345);
Countries[0].states[0].cities[1] = new city("Foo", 456);
...
Countries[3].states[6].cities[35] = new city("blah", 345);
You're trying to create new objects over and over with things like new Country
and new State
but you don't have those defined as functions. 您试图一遍又一遍地用new Country
( new State
new Country
和new State
( new State
类的东西来创建新对象,但没有将这些对象定义为函数。 Something much more simple should work: 更简单的方法应该起作用:
Countries[0].states[0].name = "Not New Hampshire";
console.log(Countries[0].states[0].name);
[Edit] : I also highly agree with upsidedown. [编辑]:我也非常赞成颠倒。 Please check a tutorial on working with data structures (arrays and objects) in JavaScript. 请查看有关使用JavaScript中的数据结构(数组和对象)的教程。
As @uʍop-ǝpısdn commented, you'll find lots of tutorials. 正如@uʍop-ǝpısdn所说,您会发现很多教程。
One of the common pattern for creating "newable" objects in JavaScript goes like this: 在JavaScript中创建“可更新”对象的常见模式之一如下:
var Country = function(name, states){
this.name = name;
this.states = states || [];
}
var State = function(name, cities){
this.name = name;
this.cities = cities || [];
}
var Countries = [];
Countries.push( new Country("USA", [ new State("NH", ...), ... ]) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.