1
我有一个函数foo
,它接收一个名为locations
的对象数组,并具有包含访问Foursquare API的信息的字符串fourSquareUrl
。我从API获取数据并将其推送到locationData
阵列。无法访问阵列的任何索引,但在完全登录时阵列能够正常工作
当我尝试访问数组的索引locationData[i]
时,我得到未定义的值。但是当我console.log(locationData);该数组显示正确。谢谢你的帮助!
var locationData = [];
function foo(locations) {
for (x in locations) {
var fourSquareUrl = 'API information';
$.getJSON(fourSquareUrl, function(data) {
var foursquareLocation = data.response.venues;
if(foursquareLocation) {
var item = foursquareLocation[0];
if (item) {
var address = item.location.formattedAddress;
locationData.push(address);
}
else {
var noAddress = "No location data available";
locationData.push(noAddress);
}
}
})
}
}
// works correctly
console.log(locationData);
// results in 'undefined'
console.log(locationData[0]);
是是异步函数,你应该添加的console.log的回调函数内(块'$ .getJSON(fourSquareUrl,功能(数据){')来获取结果。 – vitomd
太好了,谢谢! – rdtn