JavaScript 2维数组

时间:2012-07-27 16:48:06

标签: javascript multidimensional-array

我有3个阵列

var city = [
  ['Kaunas', 54.896872,23.892426],
  ['Vilnius', 54.711136,25.280685],
  ['Klaipeda', 55.720149,21.131401],
  ['Utena', 55.536403,25.59494],
];

var lake = [
  ['Ezeras Bijote', 55.785092,23.062956],
  ['Ezeras Druksiai', 55.627996,26.565228],
  ['Ezeras Sartai', 55.804368,25.832863],
  ['Ezeras Metelys', 54.300299,23.767004],
];

var shop = [
  ['Kauno Akropolis', 54.891665,23.917744],
  ['Panorama', 54.709549,25.257454],
  ['Europa', 54.687514,25.262886],
  ['Ozas', 54.638628,25.135685],
];

我想将这3个数组添加到1个数组中,不知道怎么做,如果我可以调用此类表单,bigArr[city][1]bigArr[shop][1]bigArr[lake][1],那将非常好

4 个答案:

答案 0 :(得分:1)

您可能对compact()感兴趣。

或者,只需将其声明为对象:

var myObject = {
    city: [
        ....
    ],
    lake: [
        ....
    ],
    shop: [
        ....
    ]
};

答案 1 :(得分:1)

您可能想要创建一个对象而不是多维数组 -

var bigArr = {
    "city": {
        Kaunas: {
            "lat": 54.896872,
            "lon": 23.892426 
        },
        Vilnius: {
            "lat": 54.711136,
            "lon": 25.280685
        },
        Klaipeda: {
            "lat": 55.720149,
            "lon": 21.131401
        },
        Utena: {
            "lat": 55.536403,
            "lon": 25.59494
        }
    },

    "lake": {
        ...
    },

    "shop": {
        ...
    }
}

然后你可以使用它,比如bigArr.city.Kaunas.lat

答案 2 :(得分:1)

使用您已有的:

var bigArr = {"city": city, "lake": lake, "shop": shop};

答案 3 :(得分:1)

您应该使用Objects而不是Arrays。您可以通过字符串键访问它们。将它们创建为文字:

var coordinates = {
    "city": {
        Kaunas:   [54.896872,23.892426],
        Vilnius:  [54.711136,25.280685],
        Klaipeda: [55.720149,21.131401],
        Utena:    [55.536403,25.59494]
    },
    "lake": {
        ...
    },
    "shop": {
        ...
    }
}

然后使用member operators

访问其属性
  • 点符号:coordinates.shop
  • 括号表示法:coordinates["lake"]

要获取Utena的坐标数组,您可以使用coordinates.city["Utena"]