我的数组未定义

时间:2013-04-12 12:24:54

标签: jquery html arrays leaflet

我有以下问题代码是进一步下来。 当我这样做时

city[i] = response[i].name;

我可以打印出我所拥有的每个城市的每个名字。但现在我想拥有一个多维数组,因为我还要保存以下代码

L.marker([response[i].lat, response[i].lon]).bindPopup(response[i].name);

我认为我可以将它保存在多维数组中,所以当我们以一个例子为例时

city[1]["CityName"] = "New York"
city[1]["Locations"] =  L.marker([location]).bindPopup(name);

所以,现在当我打电话给city[1]['Locations']时,我得到了L.Marker,对吧?

这是我的代码

function init()
{
region = 'all';
var url = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    attribution = "(c) OSM contributors, ODBL";

var minimal = L.tileLayer(url, {styleID: 22677, attribution: attribution});
$.ajax
({
    type: 'GET',
    url: 'webservice.php',
    data: {region: region},
    success: function(response, textStatus, XMLHttpRequest) 
    { 
        var city = new Array();
        var lygStr = '';
        for(var i = 0; i < response.length; i++)
        {
            //alert(response[i].lat + " | " + response[i].lon + " | " + response[i].name);
            alert(response[i].name);
            city[i]["CityName"] = response[i].name;

            //L.marker([response[i].lat, response[i].lon]).bindPopup(response[i].name);
            if(i + 1 == response.length)
            {
                lygStr += city[i]["CityName"];
            }
            else
            {
                lygStr += city[i]["CityName"] + ", ";
            }
        }
        alert("Test" + lygStr);
        var cities = L.layerGroup([lygStr]);

        map = L.map("map1", 
        {
            center: new L.Latlng(resposne[1].lat, response[0].lon),
            zoom: 10,
            layers: [minimal, cities]
        });
    }
});

}

3 个答案:

答案 0 :(得分:2)

正确初始化将解决此问题 - 您需要将位置city[i]处的对象初始化为保存值而不是未定义的对象。

    var city = [];   // don't use new Array() !
    var lygStr = '';
    for(var i = 0; i < response.length; i++)
    {
        city[i] = {}; // you need to create an object here

        city[i]["CityName"] = response[i].name;

另外,你想拥有一个对象而不是一个数组。数组只能有数字索引,而对象可以有你想要的标识符。

    city[i]['Location']
    // same as
    city[i].Location

答案 1 :(得分:0)

看起来就像这一行:

city[1]["Locations"] =  L.marker([location]).bindPopup(name);

您的city[1]["Locations"]将被设置为.bindPopup(name)次返回。这可以是undefined,也可以是函数。构造该方法是为了返回一个被调用的对象吗?那是怎么回事:

city[1]["Locations"] =  L.marker([location]);
city[1]["Locations"].bindPopup(name);

答案 2 :(得分:-1)

您在使用city[i]作为数组之前将其声明为:

var city = []; // don't use the new Array(); syntax
var lygStr = '';

for(var i = 0; i < response.length; i++) {
    // before using city[i] as an array, you must declare it as an array
    city[i] = [];    

    city[i]["CityName"] = response[i].name;
    ...