声明包含对象的对象数组

时间:2010-08-27 06:34:24

标签: javascript arrays

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

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

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

data =
usa
  NH
     concord: 34253
     foo: 3423
     blah: 99523
  NC
     place: 23522
Uk
  foo
     bar: 35929
     yah: 3452

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

3 个答案:

答案 0 :(得分:16)

使用对象和数组文字:

var data = {
    usa : {
        NH : {
           concord: 34253,
           foo: 3423,
           blah: 99523
        },
        NC : {
           place: 23522
        }
    },
    uk : {
      foo : {
         bar: 35929,
         yah: 3452
      }
    }
}

或更直接反映原始代码的内容:

var Countries = [ 
    {
        name : 'USA',
        states : [
            {
                name : 'NH',
                cities : [
                    {
                        name : 'Concord',
                        population : 12345
                    },
                    {
                        name : "Foo",
                        population : 456
                    }
                    /* etc .. */
                ]
            }
        ]
    },
    {
        name : 'UK',
        states : [ /* etc... */ ]
    }
]

注意:在javascript中,var foo = []完全等同于(以及首选的写作方式)var foo = new Array()。此外,var foo = {}var foo = new Object()相同。

注意:不要忘记在单独的子对象之间添加逗号。

答案 1 :(得分:4)

这对你来说是否足够好?

var data = [
  { name: "USA",
    states: [
      { name: "NH",
        cities: [
          { name: "concord", population: 34253 },
          { name: "foo", population: 3423 },
          { name: "blah", population: 99523 }
        ]
      },
      { name: "NC",
        cities: [
          { name: "place", population: 23522 }
        ]
      }
    ]
  },
  {
    name: "UK",
    states: [
      { name: "foo",
        cities: [
                  { name: "bar", population: 35929 },
                  { name: "yah", population: 3452 }
                ]
      }
    ]
  }
]

答案 2 :(得分:3)

data = {
 usa: {
   NH: {
     concord: 34253,
     foo: 3423,
     blah: 99845
   }
 uk: {
   foo: {
     bar: 3454,
     yah: 33457
   }
  }
}

}

相关问题