function createMarkers(locations, infowindow) {
// create an array of markers from Model data
for (var i = 0; i < locations.length; i++) {
// Get the position from the location array.
var position = locations[i].location;
var title = locations[i].title;
// Create a marker per location
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
address: locations[i].address,
city: locations[i].city,
url: locations[i].url,
animation: google.maps.Animation.DROP
});
// Push the marker.
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, infowindow) {
return function () {
getVenueDetails(marker.position, marker.city, marker.title, function (windowContent) {
infowindow.setContent(windowContent);
infowindow.open(map, marker);
});
};
})(marker, infowindow));
bounds.extend(position);
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
}
我正在处理我的个人项目,在下面的代码中,我收到一条错误消息 W083 不要在循环中创建一个函数 关于如何修复此错误有任何想法吗?文件: message: '在引用外部作用域变量的循环内声明的函数可能会导致语义困惑。 (W083)' 在:'99,53' 来源:'jshint' 代码:'W083'
最佳答案
不要在循环中创建函数,即使用 function
关键字是一个循环,而是创建一个变量作为对函数的引用,在我的示例中为 markerClickListener
,并将其传递给 addListener
。
function createMarkers(locations, infowindow) {
// Create the listener function
var markerClickListener = function(marker, infowindow) {
return function() {
getVenueDetails(marker.position, marker.city, marker.title, function(windowContent) {
infowindow.setContent(windowContent);
infowindow.open(map, marker);
});
};
};
// create an array of markers from Model data
for (var i = 0; i < locations.length; i++) {
// Get the position from the location array.
var position = locations[i].location;
var title = locations[i].title;
// Create a marker per location
var marker = new google.maps.Marker({
map: map,
position: position,
title: title,
address: locations[i].address,
city: locations[i].city,
url: locations[i].url,
animation: google.maps.Animation.DROP
});
// Push the marker.
markers.push(marker);
//Pass The function declared above
google.maps.event.addListener(marker, 'click', markerClickListener(marker, infowindow));
bounds.extend(position);
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
}
关于javascript - 如何避免在此循环中创建函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49205494/