Javascript 如何避免在此循环中创建函数?
Javascript 如何避免在此循环中创建函数?,javascript,jshint,Javascript,Jshint,函数createMarkers(位置,信息窗口){ //从模型数据创建标记数组 对于(变量i=0;i
函数createMarkers(位置,信息窗口){
//从模型数据创建标记数组
对于(变量i=0;i }
不要在循环中创建函数,即使用function
关键字is a loop,而是创建一个变量作为函数的引用,在我的示例中,标记ClickListener
,并将其传递给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);
}
函数createMarkers(位置,信息窗口){
//创建侦听器函数
var markerClickListener=函数(标记,信息窗口){
返回函数(){
getVenueDetails(marker.position、marker.city、marker.title、函数(windowContent){
setContent(windowContent);
信息窗口。打开(地图、标记);
});
};
};
//从模型数据创建标记数组
对于(变量i=0;i
这是一个警告,不是错误。如果代码工作正常,并且知道在这样的循环中创建函数可能会产生意想不到的副作用,则可以忽略它。