小编myf*_*wik的帖子

声明包含对象的对象数组

我有一个包含其他对象的对象数组.目前我宣布他们的方式很长.是否有更多浓缩方式来执行以下操作:

function city(name,population)
{
 this.name = name;
 this.population = population;
}

function state(name)
{
 this.name= name;
 this.cities = new Array();
}

function country(name)
{
 this.name= name;
 this.states = new Array();
}

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);
Run Code Online (Sandbox Code Playgroud)

有没有办法声明这个设置不是那么冗长,类似于xml如何布局,类似于:

data =
usa
  NH
     concord: 34253
     foo: 3423
     blah: 99523
  NC
     place: 23522
Uk
  foo
     bar: 35929
     yah: 3452
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何嵌套数组声明而不必经常重复变量名称.

javascript arrays

12
推荐指数
1
解决办法
4万
查看次数

标签 统计

arrays ×1

javascript ×1