var unique_interests = window.facebook_interests.filter((v, i, a) => a.indexOf(v) === i);
var input = map.getCenter();
var a = input.lat();
var b = input.lng();
var latlng = {lat: a, lng: b};
window.markersGP = [];
for(var i=0; i<unique_interests.length; i++)
{
var request = {
location: latlng,
radius: '500',
query: unique_interests[i]
};
console.log(request);
service = new google.maps.places.PlacesService(map);
service.textSearch(request, function (results, status){
alert(request.query);
});
}
每当调用回调函数时,for循环就完全执行了,alert()
总是打印出数组中的最后一个值。有没有办法用函数调用绑定数据?
答案 0 :(得分:0)
您可以申请IIFE模式:
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
所以代码应该是:
for(var i=0; i<unique_interests.length; i++){
var request = {
location: latlng,
radius: '500',
query: unique_interests[i]
};
console.log(request);
(function (req) {
var service = new google.maps.places.PlacesService(map);
service.textSearch(req, function (results, status){
alert(req.query);
});
})(request);
}