我需要在for循环中调用一个函数。我设法编写了一个闭包函数。但它不适合我。请帮忙解决这个问题。非常感谢您的帮助。
for(var i = 0; i < pointsData.length; i++){
(function(foo){
routeId = pointsData[i]._id;
colorId = pointsData[foo].route_color;
console.log('color start', colorId);
$.post('commands.php',{command: 'get-route-coords',id: pointsData[foo]._id}
,function(data){
MYMAP.setAllRoutes(last, coordinates, pointsData[foo].route_color);
});
}(i));
}
MYMAP.setAllRoutes = function(center,flightPlanCoordinates,colorId) {
console.log('color ids', colorId);
}
答案 0 :(得分:0)
为什么不直接在循环中运行代码,如下所示。这个要求的原因是什么?
for(var i = 0; i < pointsData.length; i++){
routeId = pointsData[i]._id;
colorId = pointsData[foo].route_color;
console.log('color start', colorId);
$.post('commands.php',{command: 'get-route-coords',id: pointsData[foo]._id} ,function(data){
MYMAP.setAllRoutes(last, coordinates, pointsData[foo].route_color);
});
}
MYMAP.setAllRoutes = function(center,flightPlanCoordinates,colorId) {
console.log('color ids', colorId);
}