我有以下问题代码在下面。 当我这样做的时候
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]
});
}
});
}
最佳答案
正确的初始化将解决这个问题 - 您需要将位于 city[i]
位置的对象初始化为一个保存您的值而不是 undefined object 。
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
关于jquery - 我的数组未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15971362/